不兼容的类型:SomeX 无法转换为 CAP#1

Xtr*_*der 5 java generics

我无法理解这里出了什么问题

import java.util.*;

class Main {
    private static class SomeX {}

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

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
Run Code Online (Sandbox Code Playgroud)

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

怎么了?(编译javac 1.8.0_102

Era*_*ran 1

如果您想允许colectionOfX包含 的任何实例SomeX,则应将其声明为:

Collection<SomeX> colectionOfX = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

当你将其声明为

Collection<? extends SomeX> colectionOfX = ...;
Run Code Online (Sandbox Code Playgroud)

Collection这意味着您可以将任何包含某种类型的元素分配给它,该类型是SomeX或 的子类SomeX

例如,您可以为其分配 a List<SomeBX>,其中SomeBXextends SomeX。在这种情况下,只能将 的实例SomeBX添加到集合中。因此,如果您尝试向集合中添加一个SomeX不是 a 的实例SomeBX(例如, 的实例SomeAX,它也是 的子类SomeX),它将是无效的。