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

查看:135
本文介绍了如何比较两个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 c $ c>如果有任何机会在哈希表中使用您的对象。 合理实施将会将对象字段的哈希码与以下内容组合:

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天全站免登陆