ArrayList集合存储学生并排序
package com.czie.iot1913.lps.genericityDemo.Collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* @author 1944900433@qq.com
* @date 2022-03-20 22:59
*/
public class ArrayTest01 {
public static void main(String[] args) {
//创建集合对象
ArrayList<Student> array = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("刘品水",21);
Student s2 = new Student("刘水",25);
Student s3 = new Student("b水",18);
Student s4 = new Student("a水",18);
//把学生添加到集合
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
//static <T> void sort(List<T> list, Comparator<? super T> c)
//根据指定的比较器指定的顺序对指定的列表进行排序。
Collections.sort(array, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num1=s1.getAge()-s2.getAge();
int num2=num1==0?s1.getName().compareTo(s2.getName()):num1;
return num2;
}
});
for (Student s:array){
System.out.println(s.getName()+","+s.getAge());
}
}
}
package com.czie.iot1913.lps.genericityDemo.Collections;
/**
* @author 1944900433@qq.com
* @date 2022-03-20 22:59
*/
public class Student {
private String name;
private int age;
public Student() {
}
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 Student(String name, int age) {
this.name = name;
this.age = age;
}
}