你不用
Comparable。您使用
Comparator。
Comparable是由对象实现的接口,用于指定它们与相同类型的其他对象的排序顺序。
Comparator是一个通用接口,只需要两个对象并告诉您它们的排序顺序。因此,您可以执行以下操作:
public class Student { private final int id; private final String name; private final int age; public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; }}与:
public class AgeComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { if (s1.getAge() == s2.getAge()) { return 0; } else { return s1.getAge() < s2.getAge() ? -1 : 1; }}和:
List<Student> students = new ArrayList<Student>();students.add(new Student(1, "bob", 15));students.add(new Student(2, "Jane", 14));students.add(new Student(3, "Gary", 16));SortedSet<Student> set1 = new TreeSet<Student>(new AgeComparator());set1.addAll(students);for (Student student : set1) { // age order}


