TreeSet可以通过传入Comparator来对对象进行排序。当使用TreeSet默认构造函数创建实例时,元素必须实现Comparable接口来提供自然排序。如果元素没有实现Comparable接口,可以通过在创建TreeSet实例时传入Comparator对象来实现排序。
例如,假设有一个Student类:
public class Student {
private int id;
private String name;
private int age;
// constructor, getters, and setters omitted for brevity
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
可以实现一个按照年龄升序排序的Comparator:
import java.util.Comparator;
public class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
}
然后,在创建TreeSet实例时传入AgeComparator即可实现按照年龄升序排序:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Student> studentSet = new TreeSet<>(new AgeComparator());
studentSet.add(new Student(1, "Alice", 18));
studentSet.add(new Student(2, "Bob", 20));
studentSet.add(new Student(3, "Charlie", 19));
System.out.println(studentSet);
}
}
输出结果为:
[Student{id=1, name='Alice', age=18}, Student{id=3, name='Charlie', age=19}, Student{id=2, name='Bob', age=20}]