ArrayList存储学生对象并排序
- 需求: ArrayList存储学生对象,使用Collections对ArrayList进行排序
- 要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
- 思路:
①定义学生类
②创建ArrayList集合对象
③创建学生对象
④把学生添加到集合
⑤使用Collections对ArrayList集合排序
⑥遍历集合
public class CollectionsDemo02 {
public static void main(String[] args) {
ArrayList<Student> array = new ArrayList<>();
Student s1 = new Student("小明", 21);
Student s2 = new Student("小红", 23);
Student s3 = new Student("小黑", 21);
Student s4 = new Student("大明", 21);
Student s5 = new Student("大大明", 22);
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
array.add(s5);
Collections.sort(array, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();;
}
});
for (Student s : array) {
System.out.println(s.getName() + s.getAge());
}
}
}
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}