Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not necessary to override both methods of interface Comparator in Java

We know that it is necessary to implement all methods of an interface, if we want to make an object of that class. But why is it not necessary to implement both the methods compare() and equals() of interface Comparator in java?

I agree that the purpose is solved but even then why is it not mandatory to override equals() if we override compare()?

like image 434
user162114 Avatar asked Oct 25 '13 06:10

user162114


People also ask

Why equals method in Comparator is not overridden?

The equals Method obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.

Can you explain why Java has both a comparable interface and a Comparator interface?

Comparable interface is used to sort the objects with natural ordering. Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided.

Why do we override compareTo method?

for example if you are writing Employee object you probably want to implement Comparable interface and override compareTo() method to compare current employee with other employees based on ID. So essentially you need to override compareTo() because you need to sort elements in ArrayList or any other Collection.

Why Comparator interface has Equals method?

Now when the javadocs talk about comparisons being "consistent with equals", then "equals" in this context always refers to the equals(Object) method of the object to be compared, may that object implement Comparable itself or just be compared to another object with a Comparator .


1 Answers

Since all classes implicitly extend Object every implementation of a Comparator has an equals method, because every Object has one.

It would be the same if you define an interface with a toString() method.

 public interface ToString {
      public String toString();
 }

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

When you look at the class it says "implements ToString" and this is true, isn't it?

like image 125
René Link Avatar answered Nov 15 '22 00:11

René Link