Comparable in java


In this post, we will see  how you can use comparable to sort list of objects in java.

Comparable interface:

Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.
For example:

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects

Java code:

For Comparable:

We will create class country having attribute id and name.This class will implement Comparable interface and implement CompareTo method to sort collection of country object by id.




Add Comment