TreeSet 实现排序的两种方式:
1,元素本身具有比较性:
public class Person implements Comparable<Person> {
private String name;
private String id;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, String id, int age) {
super();
this.name = name;
this.id = id;
this.age = age;
}
@Override
public int compareTo(Person o) {
int res1 = -(this.getAge()-o.getAge());
int res2 = this.getId().compareTo(o.getId());
int res3 = this.getName().compareTo(this.getName());
if(res1==0){
if(res2==0){
return res3;
}else{
return res2;
}
}
return res1;
}
自定义类:实现 Comparable 接口; 实现compareTo 方法使 元素本身具有比较性:
public static void main(String[] args) {
TreeSet<Student> st = new TreeSet<>();
Student s1 = new Student(11,"aw1");
Student s2 = new Student(18,"cw3");
Student s3 = new Student(19,"bw2");
Student s4 = new Student(11,"dw1");
st.add(s1);
st.add(s2);
st.add(s3);
st.add(s4);
for (Student student : st) {
System.out.println(student.getAge()+" "+student.getName());
}
2,比较器具有比较性:
public class StudentComparator implements Comparator<StudnetScore>{
@Override
public int compare(StudnetScore s1, StudnetScore s2) {
int score1 =(s1.getChinese()+s1.getEnglish()+s1.getMath()-s2.getChinese()-s2.getEnglish()-s2.getMath());
int score2 =(score1==0)?s1.getChinese()-s2.getChinese():score1;
int score3 =(score2==0)?s1.getEnglish()-s2.getEnglish():score2;
int score4 =(score3==0)?s1.getName().compareTo(s2.getName()):score3;
return score4;
}
写一个比较器 :StudentComparator 实现 comparator 泛型使 Student 实现Compare()方法:
测试代码:TreeSet<StudnetScore> ts = new TreeSet<>(new StudentComparator());
这样集合就具有了比较性:
如果这两种比较都存在,那么集合比较器优先;