public int compareTo (Module d) {
System.out.println("Comparing better");
if (priority > d.priority) return -1;
if (priority < d.priority) return 1;
return 0;
}
public int compareTo (Object d) {
System.out.println("Comparing boring");
return 0;
}
Unhappily, the prints indicate that it is the second, default method that is being called when I ask for sorting of an array of subclasses of Module. I didn't have this problem before I created the subclasses, so I'm reasonably sure this is the cause.
I tried making a compareTo method for each subclass, but it is still the generic method that is called. Does anyone have a good solution?
[java] Problem with the Comparator interface
I have a class called Module, which often needs to be sorted by priority. I therefore make it implement the Comparator interface, thus :
compareTo always takes an Object.
Source
Simply cast.
Quote:
public int compareTo(Object o)
Source
Simply cast.
public int compareTo (Object o) { Module d = (Module)o; System.out.println("Comparing better"); if (priority > d.priority) return -1; if (priority < d.priority) return 1; return 0;}
Well, a Module is-an Object, right? And as noted, it worked before I introduced the subclasses. I hate casting, I want to do polymorphism.
Quote:I tried making a compareTo method for each subclass, but it is still the generic method that is called. Does anyone have a good solution?
The problem is, as visage said, that the Comparator interface takes an object. You need to remember that you can't overload the interface method - none of those overloaded methods are defined in the interface so they aren't called. So, for each subclass you need to override compareTo by casting to that specific subclass. i.e. :
// a base classclass Base implements Comparable { // ... mind blowing stuff goes here // implement the interface public int compareTo(Object o) { // cast to the base Base b = (Base)o; // compare and return correct values }}// a derived classclass Derived extends Base { // the comparator interface is automatically // included, and because of Base we can override it // for this subclass. // Notice, however, that the method _declaration_ stays // the same, otherwise it won't be called public int compareTo(Object o) { // cast to this specific subclass Derived d = (Derived)o; // compare and return correct values }}
Cheers.
<edit :: fixed source tag.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement