是否可以在不实现Comparable类的情况下使用Comparator?例如,如果我有以下内容:
MyClass {
Comparator comp;
OrderedListInheritance(Comparator c) {
this.comp = c;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用comp来比较两个对象吗?如果是这样,我将如何做到这一点?
谢谢...
你不用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; }
}
Run Code Online (Sandbox Code Playgroud)
有:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
和:
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
}
Run Code Online (Sandbox Code Playgroud)