1.What is the Comparable interface ?
The Comparable interface is used to sort collections and arrays of objects using the
Collections.sort()
and java.utils.Arrays.sort()
methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable<T>
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the
All classes implementing the Comparable interface must implement the
compareTo()
method that has the return type as an integer. The signature of the compareTo()
method is as follows:int i = object1.compareTo(object2)
- If object1 < object2: The value of i returned will be negative.
- If object1 > object2: The value of i returned will be positive.
- If object1 = object2: The value of i returned will be zero.
2.What are the differences between the Comparable and Comparator interfaces ?
Comparable | Comparato |
---|---|
It uses the compareTo() method. int objectOne.compareTo(objectTwo). | t uses the compare() method. int compare(ObjOne, ObjTwo) |
It is necessary to modify the class whose instance is going to be sorted. | A separate class can be created in order to sort the instances. |
Only one sort sequence can be created. | Many sort sequences can be created. |
It is frequently used by the API classes. | It used by third-party classes to sort instances. |
EmoticonEmoticon