import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Test_10 {
public static void main(String[] args) {
//实例化集合对象,准备比较器 排序算法
Set<Student1> coll = new TreeSet<>(new Comparator<Student1>() {
//重写Comparator接口中的compate方法
public int compare(Student1 o1, Student1 o2) { //o1新值 o2老值
//先把成绩,降序排列
int r = o2.getScore() - o1.getScore(); //成绩降序
//如果成绩一样,名字 升序排列
if (r == 0) {
r = o1.getName().compareTo(o2.getName()); //名字升序
}
//额外处理:
//1 tom(新值) 与 其他
if ("tom".equals(o1.getName()) && !"tom".equals(o2.getName())) {
r = 1; //升序
}
//2 其他 与 tom(老值)
else if (!"tom".equals(o1.getName()) && "tom".equals(o2.getName())) {
r = -1; //降序
}
//3 tom(新值) 与 tom(老值)
if ("tom".equals(o1.getName()) && "tom".equals(o2.getName())) {
r = o2.getScore() - o1.getScore(); //成绩降序
}
return r;
}
});
//在coll集合中,add添加Student对象的信息
coll.add(new Student1("hh",65));
coll.add(new Student1("nihao",84));
coll.add(new Student1("jack",69));
coll.add(new Student1("jack",79));
coll.add(new Student1("tom",74));
coll.add(new Student1("tom",84));
coll.add(new Student1("tom",76));
coll.add(new Student1("hello",85));
coll.add(new Student1("world",77));
//遍历输出
for (Student1 s : coll) {
System.out.println(s);
}
}
}
//Student类 存学生成绩
class Student1{
private String name;
private int score;
public Student1() {
super();
}
public Student1(String name, int score) {
super();
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
}