OK. I know that Java generics can be a minefield for reckless ones, but I just came across unintuitive (for me, all the same) behavior that I was wondering about if anyone could explain: firstly, here is a class that consists of:
public class Dummy { public List<? extends Number> getList() { return new ArrayList<Number>(); } public static void main(String[] args) { Dummy dummy = new Dummy(); for (Number n: dummy.getList()) { System.out.println(n); } } }
Simple things. Now I make one change by adding a parameter of type T to Dummy:
public class Dummy<T> {
Now the class does not compile, indicating the error "Type mismatch: cannot be converted from the type of the Object element to Number" into the for () statement
It seems that since I parameterize the Dummy class, creating a new Dummy () in the main method (without specifying a type parameter) makes the type information for the getList () method no longer available: The compiler no longer knows the type of list items, so they cannot be assigned to a loop variable of type Number. Why is this type of information missing, given that the <T> declaration in the class has nothing to do with <? extends the number> declaration in the getList () method?
Also, if now I am modifying my Dummy instance as follows:
Dummy<?> dummy = new Dummy();
Then the type information becomes available again, and the class compiles again. So, why does the “Dummy of unknown type” allow you to store getList () type information, while the Dummy (supposedly unknown type, since I did not specify the parameter) loses it?
Maybe I'm Dummy :-)
source share