Possible Duplicate:
Why won't this generic java code compile?
Given the following code:
import java.util.Collections;
import java.util.List;
public class ComeGetSome {
//TODO: private final Some<?> some = new Some();
private final Some some = new Some();
public static void main(String[] args) {
new ComeGetSome().dude();
}
public void dude() {
for (String str : some.getSomeStrings()) { //FIXME: does not compile!
System.out.println(str);
}
}
}
class Some<T> {
public List<String> getSomeStrings() {
return Collections.<String> emptyList();
}
}
It does not compile because some.getSomeStrings() returns a raw List. But the method signature specify that it returns a List<String> !
Somehow it relates to the fact that Some has a type declaration but is referenced as a raw type. Using a reference to Some<?> fixes the problem. But the method has nothing to do with the type declaration on the class!
Why does the compiler behave like that?
If you use a raw (untyped) instance of a generic class, then it is treated as being completely raw, ie all generic type info is ignored, even if the type being ignored is not related to the generic type that has been omitted.
That’s why this…
…fixes the error – it uses a typed version of
Some(albeit a wildcard one)