Java Utility Library

Java Arrays - sort() Method



The java.util.Arrays.sort() method is used to sort the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Syntax

public static <T> void sort(T[] a,
                            Comparator<? super T> c)

Here, T is the type of elements in the array.


Parameters

a Specify the array to be sorted.
c Specify the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used.

Return Value

void type.

Exception

  • Throws ClassCastException, if the array contains elements that are not mutually comparable using the specified comparator.
  • Throws IllegalArgumentException, (optional) if the comparator is found to violate the Comparator contract.

Example:

In the example below, the java.util.Arrays.sort() method is used to sort a specified array of objects.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an unsorted Integer array
    Integer Arr[] = {10, 2, -3, 35, 56};

    //printing array before sorting
    System.out.print("Arr contains:"); 
    for(Integer i: Arr)
      System.out.print(" " + i);

    //creating a comparator for reverse order sorting
    Comparator<Integer> comp = Comparator.reverseOrder();

    //sort the array
    Arrays.sort(Arr, comp);

    //printing array after sorting
    System.out.print("\nArr contains:"); 
    for(Integer i: Arr)
      System.out.print(" " + i);   
  }
}

The output of the above code will be:

Arr contains: 10 2 -3 35 56
Arr contains: 56 35 10 2 -3

❮ Java.util - Arrays