java - <T extends Comparable< 有问题吗? super T>>

标签 java generics collections

我有一个三类:1.class Algorithmmax()Collection 中寻找最大值:

public class Algorithm {

    public static <T extends Comparable<T>> T max(Collection<? extends T> coll) {
        T max = coll.iterator().next();

        for (T elm : coll) {
            if (max.compareTo(elm) < 0)
                max = elm;
        }

        return max;
    }
}

2.类Fruit :

public class Fruit implements Comparable<Fruit> {
    private String name;
    private int size;

    public Fruit(String name, int size) {
        this.name = name;
        this.size = size;
    }

    public int compareTo(Fruit that) {
        if (size < that.size)
            return -1;
        else if (size == that.size)
            return 0;
        else
            return 1;
    }
}

3.类Apple扩展Fruit :

public class Apple extends Fruit {
    public Apple(int size) {
        super("Apple", size);
    }
}

现在的问题是:

public class Main
{
    public static void main(String[] args) {        
        Apple a1 = new Apple(10);
        Apple a2 = new Apple(34);

        List<Apple> apples = Arrays.<Apple>asList(a1, a2);

        System.out.println(Collections.max(apples).size);
    }
}

根据这篇文章Java - Syntax Question: What is 我应该这样写:public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll) .但它现在工作正常。为什么?类 Apple不执行 Comparable<Apple>并且没有 super .

[更新]
Java 泛型和集合书说:

Without the super wildcard, finding the maximum of a List<Apple> would be illegal, even though finding the maximum of a List<Fruit> is permitted.

最佳答案

假设我们更改了 max方法:

<T extends Comparable<T>> T max(Collection<? extends T> coll)

您将无法获得 maxList<Apple>因为Apple不执行 Comparable<Apple> , 它实现了 Comparable<Fruit> .但是你我都非常清楚 Apple知道如何将自己与另一个人进行比较Fruit因为它继承了该功能。

我们通过更改 max 的声明来解决这个问题对此:

<T extends Comparable<? super T>> T max(Collection<? extends T> coll)

这意味着我们接受任何类 T这样:

  1. T implements Comparable<T>或...
  2. T implements Comparable<X>对于一些 X这样 XT 的父类(super class)

为了找到max ,我们必须确保 T 的任何实例可以安全地接受 T 的另一个实例作为其 compare 的参数方法。

在第一种情况下,很明显 T 的任何实例可以安全地接受 T 的另一个实例作为其 compare(T) 的参数方法。

在第二种情况下,T 的任何实例可以安全地接受 T 的另一个实例作为其 compare(X) 的参数方法,因为 T 的所有实例也是 X 的实例.

您的示例说明了第二种情况,其中 T对应AppleX对应Fruit .

关于java - <T extends Comparable< 有问题吗? super T>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6704085/

相关文章:

java - 在 GWT 中将最终类变量设为静态

generics - Kotlin:难以理解泛型

Java - 为什么迭代器需要通用?

dictionary - Kotlin:集合定义的差异

python - 禁止在 collections.defaultdict 中添加键

java - 为什么Java中没有WeakList和WeakSet的实现?

java - 错误:could not create java virtual machine

Java换行选项

Java泛型名称冲突,具有相同的删除

generics - 在 Haxe 3 中正确调用泛型函数