作者:DREAM2502930781 | 来源:互联网 | 2023-02-05 14:38
参见英文答案Comparetwoobjectswith.equals()andoperator 16个我有两
参见英文答案 > Compare two objects with .equals() and == operator 16个
我有两个从同一个类实例化的java对象.
MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();
如果我将它们的两个属性设置为完全相同的值,然后验证它们是否相同
if(myClass1 == myClass2){
// objects match
...
}
if(myClass1.equals(myClass2)){
// objects match
...
}
但是,这些方法都没有返回真正的价值.我检查了每个属性并匹配.
如何比较这两个对象以验证它们是否相同?
解决方法:
您需要在MyClass中提供自己的equals()实现.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyClass)) {
return false;
}
MyClass that = (MyClass) other;
// Custom equality check here.
return this.field1.equals(that.field1)
&& this.field2.equals(that.field2);
}
如果您的对象有可能在哈希表中使用,您还应该覆盖hashCode(). reasonable implementation将把对象字段的哈希码与以下内容组合:
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 37 + this.field1.hashCode();
hashCode = hashCode * 37 + this.field2.hashCode();
return hashCode;
}
有关实现散列函数的更多详细信息,请参见this question.