views:

262

answers:

3

Hello,

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...

+3  A: 

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
}
cletus
+2  A: 

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.

daveb
This helps a lot, thank you!
behrk2
It sounds silly, but what if I do not know what type of Objects I am comparing? So if I changed the compare method to accept (Object a, Object b), is there any way I could then go ahead and compare the objects? Or check to see the type of the objects and then compare?
behrk2
@behrk - if you don't know the types of the objects, what is the meaning of "less than"? You are limited to (probably) meaningless orderings like "hash code order" and "order of toString() values".
Stephen C
A: 

Yes.

Comparator and Comparable are two separate and independent entities, only their purpose is similar.

In your code simply do: comp.compare(obj1, obj2)

Suraj Chandran