List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal
ln.add(new Float(3.1415));
In Java, Integer inherits from Number(java.lang.Number)
, so intuitively, anything that is an Integer(java.lang.Integer)
is also a number, but what that article points out is that with generics it does not work that way, because considering that example, you could end up putting a float (which is a Number) into a List<Integer>
, which is illegal because a float is not an integer.
Conclusion: Generics are not covariant.
Note: I recommend you read Effective Java (2nd Edition) Chapter 5: Generics.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…