Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Write in Covariance and Contravariance in Java Generics

Tags:

java

generics

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 ?

like image 703
Number945 Avatar asked Oct 20 '25 02:10

Number945


1 Answers

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.

like image 197
Zefick Avatar answered Oct 21 '25 16:10

Zefick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!