是否可以在不实现 Comparable 类的情况下使用比较器?例如,如果我有以下内容:
MyClass {
Comparator comp;
OrderedListInheritance(Comparator c) {
this.comp = c;
}
}
我可以使用 comp 来比较两个对象吗?如果是这样,我将如何去做呢?
谢谢...
最佳答案
您不使用Comparable
。您使用Comparator
.
Comparable
是一个由对象实现的接口(interface),用于指定它们与相同类型的其他对象的排序顺序。
Comparator
是一个通用接口(interface),它只接受两个对象并告诉您它们的排序顺序。所以你可以这样做:
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
}
关于java - 我可以在不实现 Comparable 的情况下使用 Comparator 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1864034/