package demo08.test08;
import java.util.Comparator;
import java.util.TreeSet;
import demo08.test08.Student;
public class TreeSetDemo {
public static void main(String[] args) {
// 创建TreeSet集合对象,通过比较器排序进行排序
TreeSet ts = new TreeSet(new Comparator(){
@Override
public int compare(Student s1, Student s2) {
//主要条件:
int num = s2.getSum() - s1.getSum();
//次要条件分析:
int num2 = num==0?s1.getChinese() - s2.getChinese() : num;
int num3 = num2==0?s1.getName().compareTo(s2.getName()) : num2;
return num3;
}
});
//创建学生对象
Student s1 = new Student("三百七七",100,98);
Student s2 = new Student("张缤智",100,99);
Student s3 = new Student("王焕君",99,100);
Student s4 = new Student("Aurora",98,100);
Student s5 = new Student("Ethreal",95,95);
Student s6 = new Student("Ethreal22",95,95);
//将学生添加到集合
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
for(Student s : ts){
System.out.println(s.getName()+","+s.getChinese()+","+s.getMath()+","+s.getSum());
}
}
}
public class Student {
private String name;
private int chinese;
private int math;
public Student(){}
public Student(String name, int chinese, int math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getSum() {
return this.chinese+this.math;
}
}