I want to know why the .compareTo()
is in the Comparable
interface while a method like .equals
is in the Object
class. To me, it seems arbitrary why a method like .compareTo()
is not in the Object
class already.
To use .compareTo()
, you implement the Comparable
interface and implement the .compareTo()
method for your purposes. For the .equals()
method, you simply override the method in your class, since all classes inherit from the Object
class.
My question is why is a method like .compareTo()
in an interface that you implement rather than in a class like Object
? Likewise, why is the .equals()
method in the class Object
and not in some interface to be implemented?
Best Answer
Not all objects can be compared, but all objects can be checked for equality. If nothing else, one can see if two objects exist at the same location in memory (reference equality).
What does it mean to
compareTo()
on twoThread
objects? How is one thread "greater than" another? How do you compare twoArrayList<T>
s?The
Object
contract applies to all Java classes. If even one class cannot be compared to other instances of its own class, thenObject
cannot require it to be part of the interface.Joshua Bloch uses the key words "natural ordering" when explaining why a class might want to implement
Comparable
. Not every class has a natural ordering as I mentioned in my examples above, so not every class should implementComparable
nor shouldObject
have thecompareTo
method.Effective Java, Second Edition: Joshua Bloch. Item 12, Page 62. Ellipses remove references to other chapters and code examples.
For cases where you do want to impose an ordering on a non-
Comparable
class that does not have a natural ordering, you can always supply aComparator
instance to help sort it.