arrayList中contains()方法调用indexOf()方法,indexOf()调用equals()方法,Object的equals()方法为同一,如果需要将contains()方法的同一包含修改为相等包含,需要对equals()进行覆盖,例:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
public boolean equals(Object obj) {
return (this == obj);
}
@Override
public boolean equals(Object obj) {
Song s = (Song)obj;
return this.rating == s.rating ;
}
根据程序的需要,可以写出不同的equals()方法体。
注:
//java规范: 一般重写equals方法我们都会重写hashCode方法的。
//维护 hashCode方法的常规协定,该协定声明相等对象必须具有相等的哈希码。
@Override
public int hashCode() {
return this.rating;
}