Reading the Java online tutorial I haven’t understood anything about wildcard capture.
For example:
import java.util.List;
public class WildcardError {
void foo(List<?> i) {
i.set(0, i.get(0));
}
}
Why can’t the compiler retain the assignment safely?
It knows that, by executing for instance, the method with an Integer List, it gets from i.get an Integer value. So it tries to set an Integer value at index 0 to the same Integer list (i).
So, what’s wrong? Why write Wildcard helper?
The compiler doesn’t know anything about the type of elements in
List<?> i, by definition of?. Wildcard does not mean “any type;” it means “some unknown type.”That’s true, but as I said above: the compiler can only know – at compile time, remember – that
i.get(0)returns anObject, which is the upper bound of?. But there’s no guarantee that?is at runtimeObject, so there is no way for the compiler to know thati.set(0, i.get(0))is a safe call. It’s like writing this:More reading: