This question already has answers here:
Can't add value to the Java collection with wildcard generic type
                                
                                    (4个答案)
                                
                        
                6年前关闭。
            
        

为什么不能将对象添加到集合中?由于类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/

10-09 19:43