java - 为什么第二个例子编译成功

标签 java generics

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/

相关文章:

从 NSObject 继承时,不会调用泛型中使用的 swift 子类

java - JSOUP从同名的div中获取div内容

java - Spark 框架 : Match with or without trailing slash

java - 在 XML 中初始化 TableLayout 并以编程方式填充它 - Android (java)

java - Java 中菱形运算符 (<>) 的作用是什么?

c# - UML 中的通用类型约束(where 子句)

java - Spring - 停止 bean 初始化

java - 在 Java 中不使用类创建对象

swift - 具有通用参数类型的协议(protocol)

java - 关于泛型的一些困惑