Capturing wildcards in java generics
Posted
by
Rollerball
on Stack Overflow
See other posts from Stack Overflow
or by Rollerball
Published on 2013-06-27T10:16:03Z
Indexed on
2013/06/27
10:21 UTC
Read the original article
Hit count: 208
From this orcale java tutorial:
The WildcardError example produces a capture error when compiled:
import java.util.List;
public class WildcardError {
void foo(List<?> i) {
i.set(0, i.get(0));
}
}
After this error demonstration, they fix the problem by using a helper method:
public class WildcardFixed {
void foo(List<?> i) {
fooHelper(i);
}
// Helper method created so that the wildcard can be captured
// through type inference.
private <T> void fooHelper(List<T> l) {
l.set(0, l.get(0));
}
}
First, they say that the list input parameter (i) is seen as an Object:
In this example, the compiler processes the i input parameter as being of type Object.
Why then i.get(0)
does not return an Object? if it was already passed in as such?
Furthermore what is the point of using a <?>
when then you have to use an helper method using <T>
. Would not be better using directly which can be inferred?
© Stack Overflow or respective owner