The Comparable interface

A List contains objects that you can order according to a natural order using the static method Collections.sort(List list) if the objects implement the Comparable interface.
The only method required by the Comparable interface is compareTo which has as argument an object of the same type you are sorting and the return value is an integer.
So the call to the method is:
int result = x.compareTo(y)
where x and y are objects of the same type of those in the list and result is an integer that takes the value:

  • <0 if x<y
  • ==0 if x==y
  • >0 if x>y

Look the follow example:


The output is as follows:

In the first section the list is printed in the order in which the elements have been added to the list.
In the second section you can sort with Collections.sort because the String class implements the Comparable interface and the order is alphabetic.
In the third section, the list contains objects (Country) that implement Comparable and then the sort is ascending by area because of I implemented the compareTo method.

Similarly, you can also sort the arrays using the Arrays.sort(Object[] a) method.

One Reply to “The Comparable interface”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.