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;
}
}

本文深入讲解了Java中TreeSet的两种排序方式:一是通过实现Comparable接口并覆盖compareTo方法,使元素自身具备比较性;二是利用Comparator接口,由容器自身决定排序规则。提供了详细的代码示例,帮助理解不同场景下如何灵活运用。
1878

被折叠的 条评论
为什么被折叠?



