From Effective Java by Joshua Bloch,
Cov
May be this help:-
Generics are not covariant
Arrays in the Java language are covariant -- which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[]
, and you are free to pass or assign an Integer[]
where a Number[]
is called for. (More formally, if Number is a supertype of Integer, then Number[]
is a supertype of Integer[]
.) You might think the same is true of generic types as well -- that List
is a supertype of List
, and that you can pass a List
where a List
is expected. Unfortunately, it doesn't work that way.
It turns out there's a good reason it doesn't work that way: It would break the type safety generics were supposed to provide. Imagine you could assign a List
to a List
.
Then the following code would allow you to put something that wasn't an Integer into a List
:
List li = new ArrayList();
List ln = li; // illegal
ln.add(new Float(3.1415));
Because ln is a List
, adding a Float to it seems perfectly legal. But if ln were aliased with li
, then it would break the type-safety promise implicit in the definition of li -- that it is a list of integers, which is why generic types cannot be covariant.