Java Collection Tutorial - Java Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator <? super T> c)








Syntax

Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator <? super T> c) has the following syntax.

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

Example

In the following code shows how to use Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator <? super T> c) method.

/* w w w .  j  a  v a2s. c om*/
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class Main {

   public static void main(String[] args) {

      // initializing unsorted short array
      Short sArr[] = new Short[]{3, 13, 1, 9, 21};

      System.out.println(Arrays.toString(sArr));

      // create a comparator
      Comparator<Short>  comp = Collections.reverseOrder();

      // sorting array with reverse order using comparator from 0 to 2
      Arrays.sort(sArr, 0, 2, comp);

      System.out.println(Arrays.toString(sArr));
   }
}

The code above generates the following result.