Inheritance & Lists
Class B extends class A
. I have a list of B (List<B> list1)
, but for some operations I need only class A fields, but List<A> list2 = list1
doesn't work. H开发者_如何学Cow can this problem be solved?
List<? extends A> list2 = list1;
This means "a list of a specific subtype of A
".
If you could use List<A>
, which means "a list of A an all of its subclasses", you would loose the compile time safety. Imagine:
List<B> list1 = ..;
List<A> list2 = list1;
list2.add(new C());
for (B b : list1) {
//ClassCastException - cannot cast from C to B
}
Generics are type strict , they don't support co-variant types like array.
精彩评论