Search code examples
javagenericswildcardcomparable

Compare different subtypes of a generic type T with the Comparable interface


I want to be able to write something like this:

Fruit f1 = new Apple();
Fruit f2 = new Orange();
int res = f1.compareTo(f2);

Implementing the Comparable interface in the fruit class like this:

public class Fruit<T> implements Comparable<? extends T> {

    int compareTo(T other) {
        ...
    }
}

Does not seem to work. I guess that there are some tricks with the keyword super in the wildcard...


Solution

  • You're overcomplicating it. You don't need wildcards for this:

    public class Fruit implements Comparable<Fruit> {
    
        public int compareTo(Fruit other) {
            // ...
        }
    }