Hello,大家好!我是Cx_330
本篇博文向大家演示一下如何通过集合创建并存储学生类
对象并且对学生类里面的相关信息进行特定的排序
题目描述
- 用ArrayList存储学生对象,并且按照年龄从小到大进行排序,年龄相同时,按照姓名的字母顺序排序
考察知识
-
通过Collections类对集合进行相关操作
-
根据特定的需求自己实现一个比较器方法[Comparator<>]
-
通过增强型for循环快速遍历ArrayList
源码实现
学生类源码
//首先创建一个学生类
//包括:构造方法 get/set
public 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;
}
}
存储排序学生对象源码
public class Test {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<Student>();
Student student = new Student("keke",20);
Student student1 = new Student("dingding",19);
Student student2 = new Student("huihui",18);
Student student3 = new Student("chengcehng",18);
arrayList.add(student);
arrayList.add(student1);
arrayList.add(student2);
arrayList.add(student3);
Collections.sort(arrayList, new Comparator<Student>() {//自定义排序是解题的关键
@Override//因为arrayList中存储的是学生类,不能直接简单调用sort,需要自己构建一个比较器实现排序
public int compare(Student o1, Student o2) {
int num1=o1.getAge()-o2.getAge();
int num2=num1==0?o1.getName().compareTo(o2.getName()):num1;
return num2;
}
});
for (Student s : arrayList) {
System.out.println(s.getName()+" "+s.getAge());
}
}
}
小结
- 本例主要考察我们对**比较器**的创建应用,要学会在对类对象进行排序的时候根据特定的需求,逐条分析,然后有主次的创建自己的比较器