Re: Another generics question: List<Class<?>> ls = ?
Lew wrote:
For the same reason you can't do
...snip...
Given 'Sub' extends 'Parent', it is not true that 'Foo<Sub>' extends
'Foo<Parent>'. If it did, it would allow illegal actions.
This almost makes sense to me. What I was expecting was it to work like
this:
List<?> lx = new ArrayList<String>();
lx.add( 0, "test" ); // error
String s = lx.get( 0 ); // warning, must cast
So assigning the types (the first line) is ok. That you can't put
anything into lx (second line) is fine, that's because you don't know
the actual type of lx. But you can at least get Object out. And you can
cast the Object to a String and hope you are correct.
So by analogy:
List<Class<String>> ls = new ArrayList<Class<String>>();
List<Class<?>> al1 = ls; // oops
al1.add( 0, String.class ); // works
Class<?> c = al1.get( 0 ); // works
I was expecting to work the same way. However, this time both the add
and get are ok, and it's the assignment of ls to al1 that fails. I
think I'm going to have to review my generics a bit, I've got something
mixed up.