Java案例——ArrayList儲存學生物件並排序
阿新 • • 發佈:2022-04-01
需求:ArrayList儲存學生物件,使用Collections進行排序,要求按年齡從大到小進行排序,年齡相同時按姓名的首字母排序
分析:
1.定義學生類
2.定義ArrayList集合物件
3.建立學生物件
4.將學生儲存到集合中
5.對集合排序使用Collections
6.遍歷集合
public class CollectionsDemo01 {
public static void main(String[] args) {
//建立ArrayList集合物件
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student("C三",18));
al.add(new Student("張二",17));
al.add(new Student("張四",19));
al.add(new Student("Z三",18));
//排序,需要指定comparator
Collections.sort(al, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// return 0;
int num=s1.getAge()-s2.getAge();
int num1= num==0?s1.getName().compareTo(s2.getName()):num;
return num1;
}
});
//遍歷
for (Student ss:al){
System.out.println(ss.name+ss.age);
}
}
public static class Student{
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
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;
}
}
}