Java Comparable interfaceJava Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else. compareTo(Object obj) methodpublic int compareTo(Object obj): It is used to compare the current object with the specified object. It returns
We can sort the elements of:
Collections classCollections class provides static methods for sorting the elements of collections. If collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements. Method of Collections class for sorting List elementspublic void sort(List list): It is used to sort the elements of List. List elements must be of the Comparable type. Note: String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.Java Comparable ExampleLet's see the example of the Comparable interface that sorts the list elements on the basis of age. File: Student.java File: TestSort1.java 105 Jai 21 101 Vijay 23 106 Ajay 27 Java Comparable Example: reverse orderLet's see the same example of the Comparable interface that sorts the list elements on the basis of age in reverse order. File: Student.java File: TestSort2.java 106 Ajay 27 101 Vijay 23 105 Jai 21 |