I don't understand why the following happens with Java Generics if no type is specified. Let's say we have a simple class:
public class NumberList<T extends Number> extends ArrayList<T> {
}
Then, this works fine:
NumberList<Number> list = new NumberList<Number>();
list.add(5d);
list.add(2f);
for (Number n: list) {
System.out.println(n);
}
But, if I don't specify the type, it doesn't.
NumberList list = new NumberList();
list.add(5d);
list.add(2f);
for (Number n: list) { // Error: Change type of n to Object
System.out.println(n);
}
Why the list iterator now returns Objects? Shouldn't it somehow default to the 'lowest' class (Number)? Can I force it to do that if nothing is specified?