While learning Java generics I came to know that with covariance we can read items from a structure, but we cannot write anything into it and with contravariance we can write items into a structure, but we cannot read anything from it.
Let's take an example :
List<? extends Number> myNums = new ArrayList<Integer>();
myNums.add(45L); // Covariance - compiler error
List<? super Integer> myNums = new ArrayList<Integer>();
myNums.add(1);
Number myNum = myNums.get(0); //Contravariance - compiler-error
What I am not able to understand is why is this thing prohibited ? I am not able to understand what can go wrong if this thing is allowed to happen ?
You cannot add element of Integer class into List<? extends Number> because you don't know exact type of elements in the list. It may be actually List<Double>. The same logic in the next example. What you get from List<? super Integer> may have Object type, not the Number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With