java - 不兼容类型 : SomeX cannot be converted to CAP#1

标签 java generics

<分区>

我不明白这里出了什么问题

import java.util.*;

class Main {
    private static class SomeX {}

    void doSomethingWithX(SomeX someX) {
        Collection<? extends SomeX> colectionOfX = new ArrayList<>();
        colectionOfX.add(someX);
    }
}

javac 表示如下:

  Main.java:8: error: method add in interface Collection<E> cannot be applied to given types;
          colectionOfX.add(someX);
                      ^
    required: CAP#1
    found: SomeX
    reason: argument mismatch; SomeX cannot be converted to CAP#1
    where E is a type-variable:
      E extends Object declared in interface Collection
    where CAP#1 is a fresh type-variable:
      CAP#1 extends SomeX from capture of ? extends SomeX

根据我的理解,extends 将 CAP#1 的下限限制为 SomeX 并且 SomeX 本身应该满足该限制。

怎么了? (使用 javac 1.8.0_102 编译)

最佳答案

如果你想允许 colectionOfX包含 SomeX 的任何实例,它应该声明为:

Collection<SomeX> colectionOfX = new ArrayList<>();

当你声明它为

Collection<? extends SomeX> colectionOfX = ...;

这意味着你可以给它分配任何 Collection包含某种类型的元素,即 SomeXSomeX 的子类.

例如,你可以给它分配一个List<SomeBX> , 其中SomeBX延伸SomeX .在那种情况下,只有 SomeBX 的实例可以添加到集合中。 因此,如果您尝试将 SomeX 添加到集合中不是 SomeBX 的实例(例如, SomeAX 的实例,它也是 SomeX 的子类),它将是无效的。

关于java - 不兼容类型 : SomeX cannot be converted to CAP#1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684999/

相关文章:

java - 将java作为windows服务运行的简单灵活的方法

java - 在 JAVA 中运行 Shell 或系统命令

typescript - 如何在 typescript 中用通用返回值注释函数

swift - 具有多个具有 mixin 的类的函数

java - 使用 javadoc 链接到代码线

java - 在 Oracle WebLogic Server 中针对外部服务器的常见做法是什么

java - KeyStore 未从文件初始化

c# - 如何编写包装类以使用部分泛型类型推断?

c# - 使用泛型并在接口(interface)中实现可选字段或选择性地实现接口(interface)?

java - Android 泛型错误 : The method is not applicable for the arguments