W3docs

Sort an array in Java

To sort an array in Java, you can use the Arrays.sort() method of the java.util.Arrays class. This method sorts the elements of the array in ascending order according to their natural ordering.

To sort an array in Java, you can use the Arrays.sort() method of the java.util.Arrays class. This method sorts the elements of the array in ascending order according to their natural ordering.

Here's an example of how to use the sort() method to sort an array of integers:


import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {3, 2, 1};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

This will sort the array numbers in ascending order, so it will contain the elements 1, 2, 3.

You can also use the sort() method to sort an array of objects, as long as the objects implement the Comparable interface and define a natural ordering. For example:


import java.util.Arrays;

public class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person o) {
        return Integer.compare(this.age, o.age);
    }
}

In this example, the Person class implements the Comparable interface and defines a natural ordering based on the age of the person. You can then use the sort() method to sort an array of Person objects:


import java.util.Arrays;

Person[] people = {new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 20)};
Arrays.sort(people);

This will sort the array people in ascending order based on the age of the person.

If you want to sort an array of objects in descending order, you can use the Arrays.sort() method and pass a comparator that compares the elements in reverse order. Here's an example:


import java.util.Arrays;
import java.util.Collections;

Integer[] numbers = {3, 2, 1};
Arrays.sort(numbers, Collections.reverseOrder());

This will sort the array numbers in descending order, so it will contain the elements 3, 2, 1.

Note that Arrays.sort() is stable for object arrays, meaning the relative order of equal elements is preserved. However, it is unstable for primitive arrays. If you need to sort object arrays with custom logic, you can pass a Comparator to the Arrays.sort() method.