How can arrays be sorted in Java?

In Java, you can use the sort method of the Arrays class to sort an array. This method has multiple overloaded versions, which can be used to sort arrays of different types.

Here is an example of sorting an integer array:

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 9, 1, 3};
        
        // 使用Arrays类的sort方法对数组进行排序
        Arrays.sort(numbers);
        
        // 打印排序后的数组
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

The above code will output: 1 2 3 5 9, indicating that the array has been sorted in ascending order.

For other types of arrays, similar methods can be used for sorting. It is important to note that for custom classes, it is necessary to implement the Comparable interface and override the compareTo method to specify the sorting rule.

If you need to sort according to a custom sorting rule, you can use the Comparator interface and pass in the compare method to define the sorting rule.

import java.util.Arrays;
import java.util.Comparator;

class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

public class ArraySortExample {
    public static void main(String[] args) {
        Student[] students = {
                new Student("Alice", 80),
                new Student("Bob", 70),
                new Student("Charlie", 90)
        };

        // 使用Comparator接口定义排序规则
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.getScore() - s2.getScore(); // 按成绩升序排序
            }
        });

        // 打印排序后的学生信息
        for (Student student : students) {
            System.out.println(student.getName() + ": " + student.getScore());
        }
    }
}

The above code will output:

Alice has 80, Bob has 70, and Charlie has 90.

The student information has been sorted in ascending order based on grades.

bannerAds