Can I use a Comparator without implementing Comparable?
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...
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
}
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.
Yes.
Comparator and Comparable are two separate and independent entities, only their purpose is similar.
In your code simply do: comp.compare(obj1, obj2)
精彩评论