案例:ArrayList存储学生对象并排序
public class CollectionsDemo { public static void main(String[] args) { //创建集合对象 ArrayList<Student> arrayList = new ArrayList<Student>(); //创建学生对象 Student s1 = new Student("linqingxia",30); Student s2 = new Student("zhangmanyu",35); Student s3 = new Student("wangzuxian",33); Student s4 = new Student("liuyan",33); //把学生添加到集合 arrayList.add(s1); arrayList.add(s2); arrayList.add(s3); arrayList.add(s4); //使用Collections对ArrayList集合排序 //sort(List<T> list, Comparator<? super T> c) 根据指定的比较器引起的顺序对指定的列表进行排序。 Collections.sort(arrayList, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //形参s1的实参为第二个对象-->s2 所以下面是35-30 = 5 int num = s1.getAge() - s2.getAge(); int num2 = num==0?s1.getName().compareTo(s2.getName()):num; return num2; } }); //遍历集合 for (Student s : arrayList){ System.out.println(s.getName()+","+s.getAge()); } } }
运行结果:
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。