Why there is no need to override both methods of the Comparator interface in Java

We know that it is necessary to implement all the methods of the interface if we want to create an object of this class. But why there is no need to implement both methods compare()and the equals()interface Comparatorin java?

I agree that the goal has been achieved, but even then why is it not necessary to redefine equals() if we redefine compare()?

+4
source share
3 answers

Since all classes are implicitly extended Object, each implementation of a Comparatorhas an equals method, since each Objecthas one.

, toString().

 public interface ToString {
      public String toString();
 }

 public class SomeClass implements ToString {
     // toString implicitly implemented, because Object defines it
 }

, " ToString", , ?

+7

java.lang.Object , .

+2

Object ( ) - , Java.


Comparator#equals , .

.. true, , .

However, since the coverage must be true, no overload equalsdoes not violate the new requirement.

Note that it is always safe not to override Object.equals (Object) .. [since then different instances of the comparator will never be equal].

+2
source

All Articles