java - super 通配符导致的编译错误

标签 java generics arraylist wildcard super

我对下面的代码有疑问。

你能告诉我为什么编译器拒绝接受 ty.add(new A()); 吗?毕竟 A 是 B 的父类(super class)(即符合要求)。

错误信息如下:

C.java:15: error: no suitable method found for add(A)
                ty.add(new A());
                  ^
    method List.add(int,CAP#1) is not applicable
      (actual and formal argument lists differ in length)
    method List.add(CAP#1) is not applicable
      (actual argument A cannot be converted to CAP#1 by method invocation conversion)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object super: B from capture of ? super B
1 error

这是代码(C.java):

import java.util.ArrayList;
import java.util.List;

class A
    {
    }
class B extends A
    {
    }
class C extends B
    {
    public static void main(String args[])
        {
        List<? super B> ty = new ArrayList<A>();
        ty.add(new A());
        ty.add(new B());
        ty.add(new C());
        }
    }

最佳答案

你误解了什么? super B方法。这意味着它是一个类,在编译时未知,即 BB 的父类(super class)。编译器只知道 B可以添加对象,毕竟它可能是 ArrayList<B> 。因此它必须禁止添加 A .

允许添加 A ,考虑List<? super A>List<A>对于 ty 的类型.

关于java - super 通配符导致的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19303703/

相关文章:

Swift:将类型 T 的数组传递给采用 T 协议(protocol)数组的方法

模式匹配 Map[String, Int] 中的 Scala 类型删除

java - 使用字段对类的 Arraylist 进行排序

java - 如何从 ArrayList 填充报告?

java - 无法在 tc-server 中为 db2 配置数据源

JAVA 赋值和运算符

java - 如何通过绑定(bind)映射将对象中某个名称的所有方法绑定(bind)到模板中?

java - Android Studio R似乎无缘无故没有链接

c# - 空接口(interface) vs 属性,通用约束怎么样?

Java 从原始类型 ArrayList 获取字段