Capturing wildcards in java generics
- by Rollerball
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?