Sorting using Comparable Interface

Sorting using Comparable Interface

The Comparable interface is used by the Collection.sort() method and the java.util.Array.sort() method to sort Lists and array of objects, respectively. To implement Comparable, a class must implement a single method, compareTo(). 

Here’s an invocation of compareTo():
int x = thisObject.compareTo(anotherObject)

The compareTo() method returns an int with following characteristics :

-> negative if this object < anotherObject
-> zero if this object == anotherObject
-> postive if this object > anotherObject

The sort() method uses compareTo() to determine how the List or object array should be sorted. Since we got to implement compareTo() for our own classes, we can use whatever we prefere, to sort instances for our own classes.

Let have example that shows sorting using Comparable




Sorting using Comparator interface

Leave a Reply

Your email address will not be published. Required fields are marked *