如何比较两个java对象 [英] How to compare two java objects

查看:43
本文介绍了如何比较两个java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个从同一个类实例化的 java 对象.

I have two java objects that are instantiated from the same class.

MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

如果我将它们的两个属性设置为完全相同的值,然后验证它们是否相同

If I set both of their properties to the exact same values and then verify that they are the same

if(myClass1 == myClass2){
   // objects match
   ...

}

if(myClass1.equals(myClass2)){
   // objects match
   ...

}

然而,这两种方法都没有返回真值.我检查了每个属性,它们匹配.

However, neither of these approaches return a true value. I have checked the properties of each and they match.

如何比较这两个对象以验证它们是否相同?

How do I compare these two objects to verify that they are identical?

推荐答案

您需要在 MyClass 中提供自己的 equals() 实现.

You need to provide your own implementation of equals() in MyClass.

@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().合理的实现是将对象字段的哈希码与以下内容结合起来:

You should also override hashCode() if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:

@Override
public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 37 + this.field1.hashCode();
    hashCode = hashCode * 37 + this.field2.hashCode();

    return hashCode;
}

有关实现哈希函数的更多详细信息,请参阅这个问题.

See this question for more details on implementing a hash function.

这篇关于如何比较两个java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆