将通用类型T的不同子类型与Comparable接口进行比较

Kam*_*ami 1 java generics wildcard comparable

我希望能够写出这样的东西:

Fruit f1 = new Apple();
Fruit f2 = new Orange();
int res = f1.compareTo(f2);
Run Code Online (Sandbox Code Playgroud)

在fruit类中实现Comparable接口,如下所示:

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

    int compareTo(T other) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

似乎没有用.我猜在通配符中有关键字super的一些技巧...

Anu*_*oob 5

你过度复杂了.你不需要通配符:

public class Fruit implements Comparable<Fruit> {

    public int compareTo(Fruit other) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)