Search code examples
javacollectionscomparable

Comparing the elements within the Object


When we compare the elements within the single Collection Object do we always need to override equals method? If yes why should we do that.

Actually we are comparing the elements through the CompareTo method by the integer as 1,0,-1 with their return types.


Solution

  • When we compare the elements within the single Collection Object do we always need to override equals method?

    No. You do not have to override equals(Object) in the general case. For your particular application, it may be appropriate / necessary to override equals (and hashcode), but that depends on what the non-overridden version of the method does, and what behaviour your application needs.

    Actually we are comparing the elements through the CompareTo method by the integer as 1,0,-1 with their return types.

    If you are using a Collection class that uses compareTo or compare rather than equals, then you clearly don't have to override equals. However, it is good practice for a classes equals and compareTo methods to be consistent. A future developer might assume they are consistent and get a nasty surprise when they are not. (Of course, there may be pragmatic reasons for inconsistency ... but you shouldn't let the methods be inconsistent out of laziness.)