我有两个从同一个类实例化的 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有关实现哈希函数的更多详细信息。
关于java - 如何比较两个java对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069106/