[英]How would I compare field values of two Java objects of the same but unknown type recursively?
[英]How do I compare the “state” of two objects of the same type?
我应该创建自己的equals()方法,该方法将覆盖父类的equals(method)。 此方法接受Counter对象作为其参数。 在下面的代码中,我想要一种简单的方法来确定Counter对象参数是否等于Counter类的当前实例,如果有意义的话。 我在下面的代码中通过逐个比较每个对象的字段来实现这一点,但是我想要一种更简单的方法。 看起来像这样的东西会很好:“ result =(otherCounter == new Counter(min,max)?true:false);”,但是我知道那是不对的,并且会出现错误。 如何比较两个Counter对象中变量的相等性,以便如果Counter对象c1和c2不同,则c1.equals(c2)将为false?
public boolean equals(Object otherObject)
{
boolean result = true;
if (otherObject instanceof Counter)
{
Counter otherCounter = (Counter)otherObject;
result = (otherCounter.min == this.min) &&
(otherCounter.max == this.max) &&
(otherCounter.currentCount == this.currentCount) &&
(otherCounter.rolloverOccurrence == this.rolloverOccurrence) ? true : false;
}
return result;
}
在Java中不可能发生运算符重载。 要比较两个对象是否相等,无论如何都应使用.equals()方法。 例如:obj1.equals(obj2)
这是因为有时Java API(例如:Collections)会内部调用equals方法对集合进行排序。 因此,没有简单的比较方法,只能使用equals()
您的方法像这样很好,除了您在此处得到的其他答案以外,它指出Java中没有运算符的重载, result = true
而不是false
的事情,并且注释您还记得重写hashCode
如果尚未这样做)做。 让我再给您一个建议。 该方法可以以更紧凑的方式编写:
public boolean equals(Object obj) {
if (!(obj instanceof Counter)) {
return false;
}
Counter other = (Counter) obj;
return other.min == this.min && other.max == this.max &&
other.currentCount == this.currentCount &&
other.rolloverOccurrence == this.rolloverOccurrence;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.