为什么我无法将 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/