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
()?
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.
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.
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.
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 .
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With