import java.util.*;
class Test
{
public static class Base
{
}
public static class Derived1
extends Base
{
}
public static class Derived2
extends Base
{
}
public static void main (String[] args)
{
//Example1.
List<? extends Base> e = new ArrayList<Base>();
e.add(new Derived1()); //this won't compile
//Example2.
List<? super Base> b = new ArrayList<Base>();
b.add(new Derived1()); //this compiles
}
}
最佳答案
List<? super Base> b
可以分配 List<Base>
或List<Object>
。一个Derived1
实例可以添加到两者中,因此 b.add(new Derived1())
语句通过编译。
另一方面,List<? extends Base> e
可能会被分配一个List<Derived2>
,因此编译器不允许添加 Derived1
它的实例。
关于java - 为什么第二个例子编译成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807952/