arrilist数组和collections存储学生排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<>();
Student s1 = new Student("zsf", 24);
Student s2 = new Student("jcs", 23);
Student s3 = new Student("zxt", 24);

arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);

Collections.sort(arrayList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = 0;
num = o1.getAge() - o2.getAge();
int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;


return num2;
}


});
for (Student s : arrayList) {
System.out.println("姓名 " + s.getName() + " 年龄" + s.getAge());
}

}
}

public class Student {
private String name;
private int age;

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;
}
}
posted @   想不起来好名字  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示