Java Arrays - sort() Method
The java.util.Arrays.sort() method is used to sort the specified range of the specified array of objects according to the order induced by the specified comparator. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be sorted is empty.) All elements in the range 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 range).
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, int fromIndex, int toIndex, Comparator<? super T> c)
Here, T is the type of elements in the array.
Parameters
a |
Specify the array to be sorted. |
fromIndex |
Specify the index of the first element (inclusive) to be sorted. |
toIndex |
Specify the index of the last element (exclusive) 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, if fromIndex > toIndex or (optional) if the comparator is found to violate the Comparator contract.
- Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length.
Example:
In the example below, the java.util.Arrays.sort() method is used to sort a specified range of the 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, 25}; //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 for range [1,5) Arrays.sort(Arr, 1, 5, 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 25 Arr contains: 10 56 35 2 -3 25
❮ Java.util - Arrays