Arrays.sort
Arrays.sort is a built-in method in Java that is used to sort arrays of primitive data types and objects. It sorts the elements of an array in ascending order by default, but can also sort in descending order if a custom comparator is provided.
Syntax:
There are two overloaded versions of the sort() method:
- For sorting arrays of primitive data types:
public static void sort(type[] arr)
- For sorting arrays of objects:
public static void sort(Object[] arr)
Examples:
- Sorting an array of integers in ascending order:
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); // prints [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
- Sorting an array of strings in descending order:
String[] arr = {"apple", "banana", "cherry", "date"}; Arrays.sort(arr, Collections.reverseOrder()); System.out.println(Arrays.toString(arr)); // prints [date, cherry, banana, apple]
Note: The reverseOrder() method is used to create a comparator that sorts elements in reverse order.