[英]How do I compare the “state” of two objects of the same type?
I'm supposed to create my own equals() method which overrides the equals(method) of the parent class. 我应该创建自己的equals()方法,该方法将覆盖父类的equals(method)。 This method accepts a Counter object as its argument.
此方法接受Counter对象作为其参数。 In the code below, I want an easy way to determine if the Counter object argument equals the current instance of the Counter class, if that makes sense.
在下面的代码中,我想要一种简单的方法来确定Counter对象参数是否等于Counter类的当前实例,如果有意义的话。 I have achieved this in the code below by comparing the fields of each object one by one, but I want a simpler way to do it.
我在下面的代码中通过逐个比较每个对象的字段来实现这一点,但是我想要一种更简单的方法。 Something that looks like this would be nice: "result = (otherCounter == new Counter(min,max) ? true : false);", but I know that's not right and it gets an error.
看起来像这样的东西会很好:“ result =(otherCounter == new Counter(min,max)?true:false);”,但是我知道那是不对的,并且会出现错误。 How do I compare the equality of the variables in the two Counter objects, so that c1.equals(c2) will be false if Counter objects c1 and c2 are different?
如何比较两个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;
}
Operator overloading is not possible in Java. 在Java中不可能发生运算符重载。 And to compare two object are equal or not you should use .equals() method no matter what.
要比较两个对象是否相等,无论如何都应使用.equals()方法。 Ex: obj1.equals(obj2)
例如:obj1.equals(obj2)
It is because sometimes Java API (ex: Collections) will internally call equals method to sort the collection. 这是因为有时Java API(例如:Collections)会内部调用equals方法对集合进行排序。 So there is no simple way to compare but to use equals()
因此,没有简单的比较方法,只能使用equals()
Your method is just fine like this except for the other answers you got here that state that there is not overloading of operators in Java, the thing with the result = true
instead of false
and commenting you remember to override hashCode
if you didn't already do. 您的方法像这样很好,除了您在此处得到的其他答案以外,它指出Java中没有运算符的重载,
result = true
而不是false
的事情,并且注释您还记得重写hashCode
如果尚未这样做)做。 Let me give you one more advise. 让我再给您一个建议。 The method can be written in some more compact way:
该方法可以以更紧凑的方式编写:
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.