1

I'm supposed to create my own equals() method which overrides the equals(method) of the parent class. This method accepts a Counter object as its argument. 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. 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. 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?

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;
}
shampouya
  • 386
  • 1
  • 6
  • 24
  • 7
    You should initialise `result` to `false`, because if it's not the instance of object, then it's not equal. I would say you're current implementation is just fine, sure, it's long winded, by that's the best result you're going to get – MadProgrammer Sep 05 '14 at 05:30
  • Not part of the question but don't forget the override hashCode when you override equals... – shlomi33 Sep 05 '14 at 05:57

2 Answers2

0

Operator overloading is not possible in Java. And to compare two object are equal or not you should use .equals() method no matter what. Ex: obj1.equals(obj2)

It is because sometimes Java API (ex: Collections) will internally call equals method to sort the collection. So there is no simple way to compare but to use equals()

Ravi Dasari
  • 453
  • 1
  • 4
  • 10
0

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. 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;
}
shlomi33
  • 1,458
  • 8
  • 9