Comparable interface contains only one method compareTo(T o)
and for example Collections.sort()
method first type-cast the compared object to Comparable
and then compares it.
Now I am unable to understand why we need this process in the first place. Wouldn't it be just simpler to call directly compareTo()
method of the object and get rid of the Comparable
interface? If the object doesn't have compareTo()
method it would raise an error anyway just like it does if the object didn't implement Comparable
interface.
Besides I don't see a reason one would need a Comparable
type object. Is there any advantages of having a Comparable
interface ?
If you're only calling compareTo
yourself, then it's true that there's no particular reason to implement Comparable
.
But for things like Collections.sort
and TreeSet
, those aren't hardcoded for a specific type, but they have to be able to call compareTo
on the objects you pass it to. That's what the Comparable
interface is before: implementing Comparable
means that Collections.sort
and TreeSet
know that the objects you pass them will have that method to be called. Implementing Comparable
means you can use all of the utilities that exist that need to order objects in any way, and those utilities know how to interact with your objects.