java - 无法将实现接口(interface) A 的对象添加到 Collection<?延伸 A>

标签 java generics collections

为什么我无法将 a 对象添加到集合中?因为 B 类是 A 类的扩展。

import java.util.*;

public class TestGeneric
{
  public static void main(String[] args)
  {
    Collection<? extends A> collection = new ArrayList<A>();
    A a = new B();
    collection.add(a);
  }

  private static class B implements A {
    public int getValue() { return 0; }
  }
}

interface A { int getValue(); }

最佳答案

由于以下原因:

Collection<? extends A> coll = new ArrayList<C>(); // C extends A

coll.add(new B()); // B extends A, but doesn't extend C. Oops.

但是,由于编译器知道 coll 只具有扩展 A 的元素,因此您仍然可以将它们作为 As 检索。

A myA = coll.get();  // No problem, it might be B or C, but they both extend A

关于java - 无法将实现接口(interface) A 的对象添加到 Collection<?延伸 A>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18981249/

相关文章:

asp.net-mvc - 缺少元素时的 MVC/Razor 模型绑定(bind)集合

java - 用另一个替换列表中的元素

java - a.b=c;什么时候会抛出NullPointerException?其中 a、b 和 c 都是对象

java - 为什么Java的Optional.of()不接受空值?那么它就不再是真正的 "optional"值了

java - 将构造函数类型参数放在 * 之前 * 类型是什么意思?

c# - 如何在迭代时从通用列表中删除元素?

java - 扩展通用集合

python - 不可散列对象的无序集合?

java - 在 Java 中实现多核 - 如何实现?

c# - 使用分组依据以删除重复项