Arrays.sort()
Sorts an array in place — in ascending order or by a given comparator.
Available since: Java 1.2
Syntax
static void sort(int[] a)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | int[], T[], … | The array to sort. There is a version with an index range (fromIndex, toIndex). |
| c | Comparator<? super T> | The sort order for arrays of objects. |
Return value
voidNothing — the array itself is changed.
Examples
Numbers and strings in ascending order:
void main() {
int[] numbers = {5, 2, 9, 1};
Arrays.sort(numbers);
IO.println(Arrays.toString(numbers));
String[] names = {"Oleg", "anna", "Maria"};
Arrays.sort(names);
IO.println(Arrays.toString(names));
}Output:
[1, 2, 5, 9]
[Maria, Oleg, anna]With a comparator — descending and by length:
void main() {
Integer[] numbers = {5, 2, 9, 1};
Arrays.sort(numbers, Comparator.reverseOrder());
IO.println(Arrays.toString(numbers));
String[] words = {"kiwi", "fig", "banana"};
Arrays.sort(words, Comparator.comparing(String::length));
IO.println(Arrays.toString(words));
}Output:
[9, 5, 2, 1]
[fig, kiwi, banana]Notes
The method returns nothing — int[] sorted = Arrays.sort(a) does not compile. Strings are sorted by character codes: uppercase before lowercase. A comparator only works with arrays of objects, so descending order needs Integer[], not int[].
See also
- Arrays.binarySearch() — Quickly finds a value in a sorted array by repeatedly halving it.
- Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- Comparable.compareTo() — Defines the natural order of a class — used by sort() and TreeSet.
Related recipes
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.