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:
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:
- If object1 <>
- If object1 > object2: The value of i returned will be positive.
- If object1 = object2: The value of i returned will be zero.
The Comparator interface is used to sort the elements of collections and arrays. It differs from the Comparable interface in that the Comparable interface sorts the elements only in the natural order. In contrast, the Comparator interface sorts the collections and arrays in a number of different ways.
The Comparator interface has a single compare() method, which returns an integer. It has the following signature:
- negative if Obj1 <>
- positive if Obj1 > Obj2
- zero if Obj1 == Obj2
The Comparator interface can sort only the mutually comparable objects. It cannot be used to sort primitives. Sorting elements using the Comparator interface requires building a class separate from the class whose instances are to be sorted. This is in contrast to the Comparable interface, in which case the class to be sorted itself uses the Comparable interface.
No comments:
Post a Comment