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.
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.If you are using a Collection class that uses
compareToorcomparerather thanequals, then you clearly don’t have to overrideequals. However, it is good practice for a classesequalsandcompareTomethods 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.)