java generics covariance
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.
If you could do something like this:
List<Float> foo;
List<Object> bar;
foo = new ArrayList<Float>();
bar = foo;
foo.add(1.0f);
bar.add("Hello");
things would go VERY wrong. In this example bar is an alias for foo, and if you could do it you would lose the type safety that are the main reason that generics exist.