我有一个 arrayList,我想使用 contains(Thing o) 方法来检查这两个对象是否相等,我重写了 Thing 类中的 equals() 方法,但是当我调用 contains 方法时这不起作用! 这是我的东西类:
public class Thing{
private int id;
//getter setter
@Override
public boolean equals(Object o) {
if(!(o instanceof Thing))
return false;
if(id == ((Thing)o).getId())
return true;
return false;
}
}
是否也需要覆盖 hashCode() 方法?如果是,如何覆盖它?
最佳答案
您应该覆盖 hashCode
。 ArrayList
类不使用 hashCode
方法,因此 现在 没有必要,但如果在任何时候您要使用您的类HashMap
、HashSet
或任何其他使用 hashCode
的集合,程序将中断,因为 hashCode
and equals
are not consistent .
对于这种情况,hashCode 的一个简单实现可以是:
public int hashCode() {
return id;
}
关于java - 如何在两个对象的java相等性中评估列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18286810/