The Arrays.sort()
method provides a convenient way to sort arrays of both primitive data types and objects. This method is part of the java.util.Arrays
utility class and includes overloaded versions that handle different types of data and sorting needs.
For arrays of primitive types (like int
, double
, char
), Arrays.sort()
sorts elements in ascending order by default. It uses a highly optimized algorithm for efficient sorting.
Example with an int
array:
int[] numbers = {5, 1, 4, 2, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 4, 5]
This approach works for all primitive types (int
, double
, char
, etc.) and is very fast, suitable for most applications.
For arrays containing objects, Arrays.sort()
also sorts in ascending order by default, based on the “natural order” of the elements. The objects must either implement the Comparable
interface or a custom Comparator
must be provided. Java classes like String
and Integer
implement Comparable
by default.
Example with a String
array:
String[] fruits = {"banana", "apple", "cherry"};
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits)); // Output: [apple, banana, cherry]
If you need a different order (e.g., descending order), or are sorting based on a property of an object, you can use a Comparator
.
Example with a custom comparator for descending order:
Integer[] numbers = {5, 1, 4, 2, 3};
Arrays.sort(numbers, Comparator.reverseOrder());
System.out.println(Arrays.toString(numbers)); // Output: [5, 4, 3, 2, 1]
For arrays of custom objects, create a Comparator
to define the sort criteria or have your class implement Comparable
.
Example with custom objects (e.g., sorting by age in a Person
class):
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 20)
};
// Sort by age using a custom Comparator
Arrays.sort(people, Comparator.comparingInt(person -> person.age));
System.out.println(Arrays.toString(people)); // Output: [Charlie (20), Bob (25), Alice (30)]