Kami
Kami

Reputation: 1109

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...

Upvotes: 1

Views: 468

Answers (1)

Anubian Noob
Anubian Noob

Reputation: 13596

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

public class Fruit implements Comparable<Fruit> {

    public int compareTo(Fruit other) {
        // ...
    }
}

Upvotes: 6

Related Questions