代码实现:
mport java.util.TreeSet;
public class treeset练习 {
public static void main(String[] args) {
student2 s1 = new student2("张三", 23, 90, 99, 50);
student2 s2 = new student2("李四", 24, 90, 98, 50);
student2 s3 = new student2("王五", 25, 95, 100, 30);
student2 s4 = new student2("赵六", 26, 60, 99, 70);
student2 s5 = new student2("钱七", 26, 70, 80, 70);
TreeSet<student2> treeSet=new TreeSet<>();
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
treeSet.add(s5);
// System.out.println(treeSet);//直接打印未定义排序方法会报错
for (student2 student2 : treeSet) {
System.out.println(student2);
}
}
}
class student2 implements Comparable<student2> {
private String name;
private int age;
private int chinese;
private int math;
private int english;
public student2(String name, int age, int chinese, int math, int english) {
this.name = name;
this.age = age;
this.chinese = chinese;
this.math = math;
this.english = english;
}
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 int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "student2{" +
"name='" + name + '\'' +
", age=" + age +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
@Override
public int compareTo(student2 o) {
int sum1=this.getChinese()+this.math+this.getEnglish();
int sum2=o.getChinese()+o.math+o.getEnglish();
int i=sum1-sum2;
//比较两者总分
i=i==0?this.getChinese()-o.getChinese():i;
//总分一样按照语文排序
i=i==0?this.getMath()-o.getMath():i;
// //数学一样按照语文排序
i=i==0?this.getEnglish()-this.getEnglish():i;
i=i==0?this.getAge()-o.getAge():i;
i=i==0?this.getName().compareTo(o.getName()):i;
return i;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix