codiacTushki
codiacTushki

Reputation: 750

overriding equals() vs overriding compareTo()

Why we MUST have to take an argument of type Object during overriding equals() method, but when we override compareTo() we can take an argument of the type we are sorting

   class Student implements Comparable { 
       String name; 
       int rollNum;
       // We can take here actual Student rather than Object
       public int compareTo(Object o){ 
           Student s = (Student)o; 
           return name.compareTo(o.getName());
       } 
       // We cant take an argument other than Object here
       public boolean equals(Object o){
       }
}

Upvotes: 0

Views: 515

Answers (2)

supercat
supercat

Reputation: 81169

Calling foo.equals(bar) asks, "Would you consider yourself equivalent to the object identified by this reference?" By contrast, foo.compareTo(bar) asks "Should you be supported above or below the object identified by this reference?"

Any kind of object should be able to answer the first question when given any kind of reference. If an instance of Cat is given a reference to a FordPickupTruck and asked whether it is equivalent, it wouldn't need to know anything about the FordPickupTruck class or any instances thereof, beyond the fact that an instance to one isn't an instances of Cat, to know that it wasn't equivalent to the object identified by the given reference.

The second question, by contrast, is generally only meaningful when comparing objects of the same type. A CalendarEvent class might define CompareTo such that events which have occurred or will occur sooner will sort before later events, while a Person class might define CompareTo such that people are ranked alphabetically by name. While a Person object would have no trouble determining whether it was equivalent to a particular CalendarEvent object (it would simply answer in the negative), there probably wouldn't be any meaningful way by which it could say whether it should be sorted before or after such an object.

Upvotes: 0

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

equals method is coming from Object class, which is extended by all the objects since Java 1.0. Then there was no generics and Comparable interface is used mostly the way, in which class in parametrized by itself, for example:

class Student implements Comparable <Student> {
    ....

Upvotes: 2

Related Questions