java写一个数组对象的排序
时间: 2024-06-03 10:09:34 浏览: 9
您好!针对您的问题,我可以回答。Java中可以使用Arrays类的sort方法对数组对象进行排序,代码示例如下:
int[] arr = {10, 5, 8, 20, 2};
Arrays.sort(arr); // 升序排序
System.out.println(Arrays.toString(arr)); // 输出:[2, 5, 8, 10, 20]
如果您需要对对象数组进行排序,则需要自定义比较器实现Comparator接口,覆写compare方法进行排序。例如,对一个Student类数组按照年龄升序排序的示例代码如下:
class Student {
String name;
int age;
// 省略构造方法等
}
Student[] students = {new Student("Tom", 18), new Student("Jerry", 20), new Student("Alice", 19)};
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
});
System.out.println(Arrays.toString(students)); // 输出:[Student{name='Tom', age=18}, Student{name='Alice', age=19}, Student{name='Jerry', age=20}]
希望对您有所帮助,如果还有其他问题,欢迎继续提问哦。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)