Can someone please explain why the following code is not allowed:
List<Number> l = new ArrayList<Integer>();
But I can do this:
Number[] a = new Integer[10];
I am learning generics and don’t understand this. Why does the type on the left be exactly the type from the right and child types are not allowed?
TIA!
This is a common problem for people trying to understand Generics in Java. For a detailed explanation, read the wiki article about covariance and contravariance. As your code sample demonstrates, Java’s generic classes are neither covariant nor contravariant.
Here’s a simpler, more intuitive explanation. Let’s say
was a valid declaration. Then, through polymorphism, you could give l to a function declared as
According to polymorphism,
foo(l)should be a perfectly valid call (Doubleis aNumber, after all), but you’d be adding aDoubleto anArrayList<Integer>, which understandable violates type safety.