为了更好地理解 Arrays.sort()
方法的使用,下面我们通过几个示例代码来展示不同场景下的应用。
示例一:对整型数组排序
import java.util.Arrays;
public class SortExample {
public static void main(String[] args) {
int[] array = {5, 2, 8, 1, 9, 3};
Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
输出:
Sorted array: [1, 2, 3, 5, 8, 9]
示例二:对字符串数组排序
import java.util.Arrays;
public class SortExample {
public static void main(String[] args) {
String[] array = {"banana", "apple", "orange", "grape"};
Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
输出:
Sorted array: [apple, banana, grape, orange]
示例三:对自定义对象数组排序
import java.util.Arrays;
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 other) {
return this.age - other.age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class SortExample {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
Arrays.sort(people);
System.out.println("Sorted array: " + Arrays.toString(people));
}
}
输出:
Sorted array: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]