问题
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;
}
}
Could I then use comp to compare two objects? If so, how would I go about doing that?
Thanks...
回答1:
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; }
}
with:
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;
}
}
and:
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
}
回答2:
Comparator<T>
has public int compare(T lhs, T rhs)
. So use that method to compare objects.
Also, the sorted collections will accept a Comparator
as an argument so you can (for example) say:
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override public int compare(Integer lhs, Integer rhs) {
if (rhs.intValue() < lhs.intValue())
return -1;
else if (rhs.intValue() > lhs.intValue())
return 1;
else
return 0;
}
};
new TreeMap<Integer, Integer>(comparator);
To create a tree map where the sort order is (int this case) reversed.
回答3:
Yes.
Comparator and Comparable are two separate and independent entities, only their purpose is similar.
In your code simply do: comp.compare(obj1, obj2)
来源:https://stackoverflow.com/questions/1864034/can-i-use-a-comparator-without-implementing-comparable