Sign in to follow this  
King of Men

[java] Problem with the Comparator interface

Recommended Posts

King of Men    394
I have a class called Module, which often needs to be sorted by priority. I therefore make it implement the Comparator interface, thus :
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?

Share this post


Link to post
Share on other sites
choffstein    1090
compareTo always takes an Object.
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;
}

Share this post


Link to post
Share on other sites
stormrunner    720
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 class
class 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 class
class 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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this