Type specific Comparators in JDK 5

3

Took me a few minutes today to figure out how to implement a type-specific Comparator in JDK 5, so I thought I would blog it. In JDK 5, the Comparator class is parameterized with the type of the object being compared (Comparator<T>).

I wanted to define a ThingComparator that was not paramaterized and was specific to Things, not generic. I don’t think I’ve run across the case of wanted to extend and specialize the generic-ness out of a class before now.

It turns out to be quite easy:

public class ThingComparator implements Comparator<Thing> {
    public int compare(Thing t1, Thing t2) {
        // nifty thing comparison logic
    }
}

The nice thing here is that the compare() method is defined in terms of the Comparator type (int compare(T o1, T o2)). Thus, the compare method that you are expected to implement is in terms of Thing, not in terms of Object as it would have been in JDK 1.4. And thus, no casting is necessary as the compiler will enforce that this comparator cannot be used on the wrong type.

Comments

3 Responses to “Type specific Comparators in JDK 5”
  1. Very cool. I’ve been wanting to do this for some time and didn’t know it was possible. Thank you very much!

    I had to make one change to the code above to get my comparator to work (in case it isn’t obvious).

    public class ThingComparator implements Comparator {
    public int compare(Thing t1, Thing t2) {
    // nifty thing comparison logic
    }
    }

  2. OK, the blog software stripped the change I was making out of my code and I’m guessing your code as well. Following the code “implements Comparator” should be “less than sign” for followed by “Thing” and then followed by “greater than sign”.

    I’m going to try to encode the less than and greater than characters to see if that works. If it doesn’t, then please ignore the following…

    public class ThingComparator implements Comparator<Thing> {
    public int compare(Thing t1, Thing t2) {
    // nifty thing comparison logic
    }
    }

  3. Alex says:

    Exactly right, Rob! That’s perhaps the most important detail in the example, too! Fixed now in the post.

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!