Hello. Wikipedia and other articles tell us that a record of the sort List<? super Number> List<? super Number> contravariant. However, in such a sheet I can freely add not only the ancestors of the Number , but also any successors of the Number , for example, Integer , and this is already covariance. It turns out that both properties work. That is, we can not say that the very first record is only contravariant, right?
- As far as I understand, the Integer in this case will not be inserted as an Integer, but as a Number or Object, because they are, too. - etki
|
1 answer
Countervariance is of type List<? super Number> List<? super Number> entirely, and not just to the type of the elements of this list.
Here is a simple example.
public void doIt() { List<Integer> listOfInteger = new LinkedList<>(); List<Number> listOfNumber = new LinkedList<>(); List<Object> listOfObject = new LinkedList<>(); contr(listOfInteger); // ошибка contr(listOfNumber); contr(listOfObject); } public void contr(List<? super Number> l) { l.add(1); Object object = l.get(0); Number number = l.get(0); // ошибка } |