I thought I understood this but obviously not…
I have a method signature like so:
void doSomething(List<TypeA> typeAs){...}
List<TypeA<TypeB>> getTypeBTypeAs(){...}
but if I try and call
doSomething(getTypeBTypeAs());
I get a compile error: “the method doSomething(List) in the type … is not applicable for the arguments (List>)”
however if i change the sig of doSomething to
void doSomething(List<TypeA<?>> typeAs){...}
it still doesn’t work, but
void doSomething(List typeAs){...}
obviously it works as i bypass generics.
which seems odd.
Can someone fill me in?
Also, in this case I’d like doSomething to work with any List containing TypeAs of any generic type; undefined, TypeB, TypeC etc.
thanks.
A generic class
TypeA<TypeB>is a different type fromTypeA. You can’t pass in a parameter of typeTypeA<TypeB>where the method expects aTypeA. AlsoTypeA<TypeB>is a different type fromTypeA<TypeC>, so the same constraints apply.The classic example (from Effective Java, 2nd Ed. AFAIR) is: we have containers for animals (
Container<Animal>) and as subclasses ofAnimalwe haveLionandButterfly. Now, if you have a methodit will accept both lions and butterflies. However, this function
will not accept a
Container<Lion>, neither aContainer<Butterfly>. Do realize that a strong cage useful for keeping lions safely would not stop butterflies from flying away, and vice versa a thick but light net to hold butterflies would not stand a chance against a lion.If you really are sure that any kind of animal container suits you, declare your function like this:
Back to your case, I guess the only method to accept both
List<TypeA>andList<TypeA<TypeB>>would be something like this: