How come, in Java, I can write
List> list = new LinkedList();
but not
List>
Each parameterization must be wildcarded:
List<? extends Container<?>> list = new LinkedList<Container<Double>>();
Edit: I was searching through Angelika Langer's FAQ for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages).
The way to think about this is that each parameterization is independent, and the compiler will not infer information about the parameterization unless you explicitly say to do so.
Edit: I was searching through Angelika Langer's FAQ for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages).
Thank you very much for the answer. I found an explanation in the FAQ, and after some squinting at it I think I get it.
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#What%20do%20multilevel%20wildcards%20mean?
Consider what would happen if you could.
List<Container<Double>> list1 = new LinkedList<Container<Double>>();
List<Container<?>> list2 = list1; // this shouldn't be allowed, because of the below
Container<String> foo = new Container<String>();
foo.add("hi");
list2.add(foo); // legal, because Container<String> is a subtype of Container<?>
Container<Double> bar = list1.get(0);
Double x = bar.get(0); // type error; it is actually a String object
// this indicates that type safety was violated
However, using List<? extends Container<?>>
doesn't have this problem because you cannot put anything (except null
) into a list of this type (because there is no type that is guaranteed to be a subtype of "? extends Container<?>
").