我有一个父类A,而它的子类B。这两个摘要之间有什么区别:
public static void main (String[] args) {
ArrayList<? super A> e = new ArrayList<>();
B thing = new B();
e.add(thing);
System.out.println(e.get(0));
}
public static void main (String[] args) {
ArrayList<A> e = new ArrayList<>();
B thing = new B();
e.add(thing);
System.out.println(e.get(0));
}
答案 0 :(得分:3)
ArrayList<? super A>
和ArrayList<A>
之间的区别在于,可以为前者分配ArrayList<T>
的对象,其中T
是A
或{{ 1}}本身。
具体来说,这是有效的:
A
这不是:
ArrayList<? super A> listOfSuperA = new ArrayList<Object>();
这意味着您可以从ArrayList<A> listOfA = new ArrayList<Object>();
和listOfA
中获得不同类型的值:
listOfSuperA
This might be useful if you want to learn more about where to use ? super T