I know that there is one method in Interface Comparable<T>
, that is compareTo()
. I assume that it's just a function name without any implementation in it and when any class implements Comparable interface, that class have to override that method. But then I read the Docs
and find out that Comparable also return a value, int, and has its own implementation without the need of overriding it in the implementing class.
Eg, this example:
public static <T extends Comparable<T>> T max(T a, T b) {
if (a == null) {
if (b == null) return a;
else return b;
}
if (b == null)
return a;
return **a.compareTo(b)** > 0 ? a : b;
}
Comparable is an interface meaning that objects that implement it must implement its method. You are right in that it only has one method to implement compareTo(T o). You are also right about the method returning an integer. compareTo returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The reason an interface like this exists is to make java more generic. Since the interface defines a standard name and basis for comparing, this standard can then be used in other methods such as Collections.sort or Collections.binarySearch. This way if you want to sort 500 objects you just created in a Vector, all you have to do is implement compareTo(T o), and then you could call Collections.sort(myVector).
I think you are getting confused with the fact that some objects already implement the interface Comparable such as Integer, String, UUID, or CharBuffer. These ones will work 'out of the box', but if you try to pass a Vector of JPanels (a class that does not implement Comparable) to Collections.sort, you will get an error.