Comparator vs Comparable in Java

Comparator Vs Comparable in Java

In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types of objects that are not comparable, Java provides Comparator and Comparable interfaces.

Sorting Primitive data types

To sort primitive data types like integer array and String array, Java provides Arrays.sort() method. The following program demonstrates the use of the sort() method.

SortingPrimitivedt.java

import java.util.*;

public class SortingPrimitivedt

{

/* Driver Code */

public static void main(String ar[])

{

int[] intarray = {5,9,6,12};

System.out.println(“Before Sorting integer array: “+Arrays.toString(intarray));

/* sorting integer array. */

Arrays.sort(intarray);

System.out.println(“After Sorting integer array: “+Arrays.toString(intarray));

String[] strarray = {“A”, “K”, “B”, “H”, “E”};

System.out.println(“Before Sorting String array: “+Arrays.toString(strarray));

/* sorting String array. */

Arrays.sort(strarray);

System.out.println(“After Sorting String array: “+Arrays.toString(strarray));

}

}

Output:

Before Sorting integer array: [5, 9, 6, 12]

After Sorting integer array: [ 5, 6, 9, 12]

Before Sorting String array: [A, K, B, H, E]

After Sorting String array: [A, B, E, H, K]

Here, the intarray and strarray are sorted using Array.sort() method available in java.util package. And the result is displayed on the screen using the Arrays.toString() method.