I was looking at the Java Generics documentation and found this piece of code,
public class WildcardError {
void foo(List<?> l) {
//This give a compile time error
l.set(0,l.get(0));
}
}
I can understand that we are fetching an element from a List<?>
and trying to set it to another List<?>
. So the compiler gives an error. My question is it makes sense when the 2 lists are different i.e. l.set(0, m.get(0))
here lists l
and m
are different. But in the above example, l
and l
are the same lists. Why isn't the compiler smart enough to see that? Is it hard to implement it?
Edit:
I am aware that I can fix it by a helper method or by using T
instead of a ?
. Just wondering why compiler doesn't do it for me.