我可以在不实施Comparable的情况下使用比较器吗? [英] Can I use a Comparator without implementing Comparable?
问题描述
是否可以在不实现Comparable类的情况下使用Comparator?例如,如果我有以下内容:
Is it possible to use a Comparator without implementing the Comparable class? For instance, if I had the following:
MyClass {
Comparator comp;
OrderedListInheritance(Comparator c) {
this.comp = c;
}
}
我可以用comp比较两个物体?如果是这样,我将如何去做?
Could I then use comp to compare two objects? If so, how would I go about doing that?
谢谢...
推荐答案
您不使用< a href = http://www.j2ee.me/javase/6/docs/api/java/lang/Comparable.html rel = noreferrer> 可比较
。您使用 比较器
。
You don't use Comparable
. You use Comparator
.
可比较
是由对象实现的接口,用于指定它们与其他对象的排序顺序相同类型的对象。
Comparable
is an interface implemented by objects to specify their sort order with other objects of the same type.
比较器
是一个通用接口,它仅接受两个对象并告诉您它们的排序顺序。因此,您可以这样做:
Comparator
is a generic interface that simply takes two objects and tells you their sort order. So you can do:
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
}
这篇关于我可以在不实施Comparable的情况下使用比较器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!