java - Why use a wild card capture helper method? -
referring : wildcard capture helper methods
it says create helper method capture wild card.
public void foo(list<?> i) { foohelper(i); } private <t> void foohelper(list<t> l) { l.set(0, l.get(0)); }
just using function below alone doesn't produce compilation errors, , seems work same way. don't understand is: why wouldn't use , avoid using helper?
public <t> void foo(list<t> l) { l.set(0, l.get(0)); }
i thought question boil down to: what's difference between wildcard , generics? so, went this: difference between wildcard , generics. says use type parameters:
1) if want enforce relationship on different types of method arguments, can't wildcards, have use type parameters.
but, isn't wildcard helper function doing? not enforcing relationship on different types of method arguments setting , getting of unknown values?
my question is: if have define requires relationship on different types of method args, why use wildcards in first place , use helper function it?
it seems hacky way incorporate wildcards.
in particular case it's because list.set(int, e) method requires type same type in list.
if don't have helper method, compiler doesn't know if ?
same list<?>
, return get(int)
compiler error:
the method set(int, capture#1-of ?) in type list<capture#1-of ?> not applicable arguments (int, capture#2-of ?)
with helper method, telling compiler, type same, don't know type is.
so why have non-helper method?
generics weren't introduced until java 5 there lot of code out there predates generics. pre-java 5 list
list<?>
if trying compile old code in generic aware compiler, have add these helper methods if couldn't change method signatures.
Comments
Post a Comment