在学习的过程中,发现Vector的有些方法看起来差不多,比较疑惑。
1.有两个增加元素的方法add()和addElement(),。
通过查看源代码和API文档比较:
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
发现:
(1)add()方法有返回值,而addElement()方法没有返回值。
(2)add(Object o)是List接口中声明的方法,在Vector里实现。
2.clear()、removeAllElements()、removeAll(Collection<?> c)的区别
API文档中是这样解释的:
clear()
从此向量中移除所有元素。
removeAllElements()
从此向量中移除全部组件,并将其大小设置为零。
removeAll(Collection<?> c)
从此向量中移除包含在指定 Collection 中的所有元素。
查看源代码比较:
public void clear() {
removeAllElements();
}
public synchronized void removeAllElements() {
modCount++;
// Let gc do its work
for (int i = 0; i < elementCount; i++)
elementData[i] = null;
elementCount = 0;
}
public synchronized boolean removeAll(Collection<?> c) {
return super.removeAll(c);
}
Vector继承自AbstractList , AbstractList继承自AbstractCollection,removeAll在该类中定义。
public boolean removeAll(Collection<?> c) {
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
public boolean remove(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}
看到一哥们的程序就出在这里了
(传)如何使用Java List等集合类的removeAll方法
http://blog.csdn.net/will_awoke/article/details/6528872
可以看到在调用removeAll方法时,实际上是循环调用了remove方法,而remove方法中有一段关键的代码:
if (o.equals(it.next())
因为上述例子中的实体类没有Override hashCode和equals方法 !而在执行removeAll方法时是通过equals方法来判断集合元素是否相等的,如果没有Override equals方法,其默认的仍是比较对象,所以会出现上述问题!
太困了,明天继续搞懂这个。
话说今天值班时候拿了本最薄的Effective java去学办看,正好看到了2条.
1:覆盖equals时请遵守通用约定
2:覆盖equal是()时要记得重写hashCode()之类的。
Zzz
----------------------------------------------------------------------------------------------------------------------------------
2014-3-6
Object中的equals方法
public boolean equals(Object obj) {
return (this == obj);
}