使用List.contains(Object object)
方法判断ArrayList是否包含一个元素对象(针对于对象的属性值相同,但对象地址不同的情况),如果没有重写List的元素对象Object中的equals方法,默认如下:
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return super.equals(o);
}
将导致contains方法始终返回false。
查看ArrayList的contains方法的源码如下:
/**
* Searches this {@code ArrayList} for the specified object.
*
* @param object
* the object to search for.
* @return {@code true} if {@code object} is an element of this
* {@code ArrayList}, {@code false} otherwise
*/
@Override public boolean contains(Object object) {
Object[] a = array;
int s = size;
if (object != null) {
for (int i = 0; i < s; i++) {
if (object.equals(a[i])) {
return true;
}
}
} else {
for (int i = 0; i < s; i++) {
if (a[i] == null) {
return true;
}
}
}
return false;
}
可以看出,contains方法依据Object的equals方法来判断是否包含某一元素,继续查看Object类中的equals方法,源码如下:
public boolean equals(Object o) {
return this &