views:

35

answers:

1

Given:

public interface PrimaryKey<Key extends Comparable> {
    Key getKey();
}

and

public class PrimaryKeyComparator implements Comparator<PrimaryKey> {
    public int compare(PrimaryKey first, PrimaryKey second) {
        return first.getKey().compareTo(second.getKey());
    }
}

This combination works, but gives warnings about raw types. I've tried various ways of adding the type arguments, but every combination I've tried breaks the code.

+3  A: 

Try this:

public interface PrimaryKey<TKey extends Comparable<TKey>> {
    TKey getId();
}

public class PrimaryKeyComparator<TKey extends Comparable<TKey>> 
                                 implements Comparator<PrimaryKey<TKey>> {
    public int compare(PrimaryKey<TKey> first, PrimaryKey<TKey> second) {
        return first.getId().compareTo(second.getId());
    }
}
bruno conde
Awesome! Thank you.
Paul Croarkin
The generic parameter `TKey` should really be `<K extends Comparable<? super K>>` which allows the use of classes that implement the raw `Comparable` and not `Comparable<T>`, or subclasses of a `Comparable<T>` class.
ColinD