arraylist对象排序
时间: 2023-07-22 15:36:56 浏览: 99
如果需要对一个存储自定义对象的`ArrayList`进行排序,需要实现该对象的`Comparable`接口,并重写`compareTo`方法来指定对象的排序规则。例如,假设有一个存储学生信息的类`Student`,其中包含学生的姓名和年龄信息,可以按照学生的年龄从小到大排序,代码如下:
```java
import java.util.ArrayList;
import java.util.Collections;
public class Example {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("Tom", 18));
list.add(new Student("Jack", 20));
list.add(new Student("Lucy", 16));
list.add(new Student("Alice", 19));
list.add(new Student("Bob", 17));
Collections.sort(list);
for (Student student : list) {
System.out.println(student.getName() + " " + student.getAge());
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student student) {
return this.age - student.getAge();
}
}
```
输出结果为:
```
Lucy 16
Bob 17
Tom 18
Alice 19
Jack 20
```
如果需要按照从大到小的顺序进行排序,只需要在`compareTo`方法中将比较条件改为`student.getAge() - this.age`即可。
阅读全文