javacovariance

Covariance in Java - Collection cannot be added to


I was reading an interesting dzone article on covariance in java which is pretty easy to follow but there is one thing bugging me which doesn't make sense, the article is here https://dzone.com/articles/covariance-and-contravariance

I am quoting examples from the article here where it is explaining why a collection cannot be added to:

With covariance we can read items from a structure, but we cannot write anything into it. All these are valid covariant declarations.

List<? extends Number> myNums = new ArrayList<Integer>();

Because we can be sure that whatever the actual list contains, it can be upcasted to a Number (after all anything that extends Number is a Number, right?) However, we are not allowed to put anything into a covariant structure.

myNums.add(45); //compiler error

This would not be allowed because the compiler cannot determine what is the actual type of the object in the generic structure. It can be anything that extends Number (like Integer, Double, Long), but the compiler cannot be sure what

The paragraph above is what doesn't make sense to me, the compiler knows that the list contains Number or anything that extends it, and the ArrayList is typed to Integer. And the compiler knows about the literal int that is inserted.

So why does it enforce this as it seems to me like it can determine the type?


Solution

  • You are missing two points: