列举多个例子生动形象地详细说明Java中ARRAYSSORT
在Java中,Arrays.sort()方法用于对数组进行排序。下面是一些例子来生动形象地详细说明Arrays.sort()的用法。
- 对整数数组排序:
int[] numbers = {5, 2, 9, 1, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
输出:[1, 2, 3, 5, 9]
- 对字符串数组按字母顺序排序:
String[] names = {"John", "Alice", "Bob", "Charlie"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
输出:[Alice, Bob, Charlie, John]
- 对自定义对象数组按照某个属性排序:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Person[] people = {new Person("John", 25), new Person("Alice", 30), new Person("Bob", 20)};
Arrays.sort(people, Comparator.comparing(Person::getAge));
System.out.println(Arrays.toString(people));
输出:[Person{name='Bob', age=20}, Person{name='John', age=25}, Person{name='Alice', age=30}]
- 对多维数组排序:
int[][] matrix = {{5, 2, 9}, {1, 3, 7}, {4, 8, 6}};
Arrays.sort(matrix, Comparator.comparingInt(a -> a[0]));
System.out.println(Arrays.deepToString(matrix));
输出:[[1, 3, 7], [4, 8, 6], [5, 2, 9]]
这些例子展示了Arrays.sort()方法在不同场景下的使用。它可以对基本类型数组和对象数组进行排序,并且可以根据不同的比较器来实现不同的排序规则。
原文地址: https://www.cveoy.top/t/topic/i6Jv 著作权归作者所有。请勿转载和采集!