TreeSet 的排序方式
一
让元素本身具有比较性,需要实现Comparable接口
覆盖compareTo方法
class Student implements Comparable{ //重写compareto方法进行排序
int age;
String name;
Student(String name,int age){
this.name=name;
this.age=age;
}
public String toString() {
return name+age;
}
@Override
public int compareTo (Object obj) {
Student obj1=(Student)obj;
int num=this.age-obj1.age;
return num==0?this.name.compareTo(obj1 .name):num;
}
}
public class TreeSetTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Student> set=new TreeSet<>();
set.add(new Student("fdk",21));
set.add(new Student("hah",21));
set.add(new Student("fdk",24));
Iterator<Student> it=set.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println(s);
}
}
}
二
让容器自身具有比较性 ,需要实现Comparator接口,覆盖compare
public class TreeSetTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
BySortage sort=new BySortage(); //重写comparator排序
TreeSet<Student> set=new TreeSet<>(sort);
set.add(new Student("fdk",21));
set.add(new Student("hah",21));
set.add(new Student("fdk",24));
Iterator<Student> it=set.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println(s);
}
}
}
class BySortage implements Comparator<Student>{
@Override
public int compare(Student stu1, Student stu2) {
int num=stu1.age-stu2.age;
return num==0?stu1.name.compareTo(stu2.name):num;
}
}
class Student {
int age;
String name;
Student(String name,int age){
this.name=name;
this.age=age;
}
public String toString() {
return name+age;
}
}