我有一个父类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));
}
ArrayList<? super A>
和ArrayList<A>
之间的区别在于,可以为前者分配ArrayList<T>
的对象,其中T
是A
或A
本身的超类。
具体来说,这是有效的:
ArrayList<? super A> listOfSuperA = new ArrayList<Object>();
这不是:
ArrayList<A> listOfA = new ArrayList<Object>();
这意味着您可以从listOfA
和listOfSuperA
中获得不同类型的值:
A a = listOfA.get(0); // valid
Object o = listOfA.get(0); // valid, because A can be converted to Object.
A a2 = listOfSuperA.get(0); // invalid, because listOfSuperA could contain Objects, which are not convertible to A
Object o2 = listOfSuperA.get(0); // valid, because whatever is in listOfSuperA, it can be converted to Object
This might be useful if you want to learn more about where to use ? super T