Java Generics: assignment with nested wildcard parameters -
for next code sample:
public static class abc<x> { } public static class def<y> { } public static class ghi<z> { } public void dothis() { list<?> listone; list<abc<?>> listtwo; list<abc<def<?>>> listthree; list<abc<def<ghi<?>>>> listfour; list<abc<def<ghi<string>>>> listfive; abc<def<ghi<string>>> abcdef; abcdef = new abc<def<ghi<string>>>(); listone.add(abcdef); // line 1 listtwo.add(abcdef); // line 2 listthree.add(abcdef); // line 3 listfour.add(abcdef); // line 4 listfive.add(abcdef); // line 5 } lines 1, 3, , 4 not compile:
(line 1)
the method add(capture#1-of ?) in type list<capture#1-of ?> not applicable arguments (abc<def<ghi<string>>>) (line 3)
the method add(abc<def<?>>) in type list<abc<def<?>>> not applicable arguments (abc<def<ghi<string>>>) (line 4)
the method add(abc<def<ghi<?>>>) in type list<abc<def<ghi<?>>>> not applicable arguments (abc<def<ghi<string>>>) lines 2 , 5, however, compile.
could explain why lines 1, 3, , 4 not legal assignments? , if wildcard parameters cannot used in way on lines, why assignment on line 2 legal?
listone.add(abcdef) (line 1) invalid because list<?> represents list of unknown specific type. example, list<string>, wouldn't want add together isn't string. compiler error happens because abc<def<ghi<string>>> not assignable ?.
listtwo.add(abcdef) (line 2) valid because list<abc<?>> represents list of abcs of any type. that's right - nested wildcards different top-level wildcards in represent type rather specific type (in other words, nested wildcards don't capture). compiler allows because abc<def<ghi<string>>> assignable abc<?>. see post farther give-and-take of nested wildcards: multiple wildcards on generic methods makes java compiler (and me!) confused
listthree.add(abcdef) (line 3) invalid because list<abc<def<?>>> represents list of abcs of defs of type. generics not covariant, abc<def<ghi<string>>> not assignable abc<def<?>>, though def<ghi<string>> assignable def<?>. list<integer> isn't assignable list<number> same reason. see post farther explanation: is list<dog> subclass of list<animal>? why aren't java's generics implicitly polymorphic?
listfour.add(abcdef) (line 4) invalid same reason - abc<def<ghi<string>>> not assignable abc<def<ghi<?>>>.
listfive.add(abcdef) (line 5) valid because generic types match - abc<def<ghi<string>>> assignable abc<def<ghi<string>>>.
java generics type-parameter nested-generics
No comments:
Post a Comment