Java Comparable interface is used to compare objects and sort them according to the natural order.
Natural ordering is referred to as its compareTo()
function. The string objects are sorted lexicographically, and the wrapper class objects are sorted according to their built-in compareTo()
function (like how Integers objects are sorted in ascending order).
The compareTo()
function compares the current object with the provided object. This function is already implemented for default wrapper classes and primitive data types; but, this function also needs to be implemented for user-defined classes.
It returns:
a positive integer, if the current object is greater than the provided object.
a negative integer, if the current object is less than the provided object.
zero, if the current object is equal to the provided object.
Once the compareTo()
function is implemented in the class, either Collections.sort()
or Arrays.sort()
is called for sorting in the driver function.
Collection.sort()
vs Array.sort()
1.Collection.sort()
is used to sort a list of objects.
2.Array.sort()
is used to sort an array of objects.
Collections.sort()
:// Using Collections.sort() to sort list.import java.util.*;public class Collectionsort{public static void main(String[] arguments){ArrayList<String> list = new ArrayList<String>();list.add("E");list.add("D");list.add("U");list.add("C");list.add("A");list.add("T");list.add("I");list.add("V");list.add("E");//printing list without sortingSystem.out.println(list);//sorting listCollections.sort(list);//printing list after sortingSystem.out.println(list);}}
Collection.sort()
:// Using Collections.sort() to sort list.import java.util.*;public class Collectionsort{public static void main(String[] arguments){ArrayList<Integer> list = new ArrayList<Integer>();list.add(2);list.add(4);list.add(0);list.add(1);list.add(3);//printing list without sortingSystem.out.println(list);//sortingCollections.sort(list);//printing list after sortingSystem.out.println(list);}}
// importing librariesimport java.util.*;import java.lang.*;import java.io.*;class Student implements Comparable <Student>{int id;String name;//student classpublic Student (int id, String name){this.id=id;this.name=name;}//printing functionpublic String toString(){return this.id + " " + this.name;}// compareTo() function defined.// sorting them by their id'spublic int compareTo(Student std){return this.id - std.id;}}// Driver functionclass Main{public static void main (String[] arguments){ArrayList <Student> list = new ArrayList <Student> ( );list.add(new Student(2, "Bob"));list.add(new Student(1, "Aaron"));list.add(new Student(3, "Carl"));//printing unsortedfor (int i=0; i<list.size(); i++)System.out.println(list.get(i));//sorting.Collections.sort(list);//printing after sortingSystem.out.println("\n");for (int i=0; i<list.size(); i++)System.out.println(list.get(i));}}
Free Resources