package com.TreeSet排序案例01;
import java.util.TreeSet;
public class main {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
Student s1 = new Student("aa",90,58);
Student s2 = new Student("bb",60,45);
Student s3 = new Student("cc",58,25);
Student s4 = new Student("cc",16,37);
Student s5 = new Student("dd",35,96);
Student s6 = new Student("ee",25,45);
Student s7 = new Student("ff",45,25);
Student s8 = new Student("gg",45,25);
Student s9 = new Student("hh",60,10);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);
ts.add(s8);
ts.add(s9);
for (Student s : ts) {
System.out.println(s.getName() + ",语文:" + s.getChinese() + ",数学:" + s.getMath() + ",总分:" + s.getSum());
}
}
}
有参构造中的Sum = chinese+math;不要忘了加
package com.TreeSet排序案例01;
public class Student implements Comparable<Student> {
private String name;
private int Chinese;
private int Math;
private int Sum;
public Student() {
}
public Student(String name, int chinese, int math) {
this.name = name;
Chinese = chinese;
Math = math;
Sum = chinese+math;
}
public int getSum() {
return Sum;
}
public void setSum(int chinese, int math) {
Sum = chinese + math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return Chinese;
}
public void setChinese(int chinese) {
Chinese = chinese;
}
public int getMath() {
return Math;
}
public void setMath(int math) {
Math = math;
}
@Override
public int compareTo(Student o) {
int i = this.Sum - (o.Math + o.Chinese);
int i1 = i == 0 ? o.name.compareTo(this.name):i;
return i1;
}
}
输出结果为:
cc,语文:16,数学:37,总分:53
hh,语文:60,数学:10,总分:70
gg,语文:45,数学:25,总分:70
ff,语文:45,数学:25,总分:70
ee,语文:25,数学:45,总分:70
cc,语文:58,数学:25,总分:83
bb,语文:60,数学:45,总分:105
dd,语文:35,数学:96,总分:131
aa,语文:90,数学:58,总分:148