List <? super B> lsb = new ArrayList <a> (); Logical error in java?

We have:

class A{}
class B extends A{}
class C extends B{}
class D extends C{}

we can define lists like:

List<? super B> lsb1 = new ArrayList<Object>();
//List<? super B> lsb2 = new ArrayList<Integer>();//Integer, we expect this    
List<? super B> lsb3 = new ArrayList<A>();
List<? super B> lsb4 = new ArrayList<B>();
//List<? super B> lsb5 = new ArrayList<C>();//not compile
//List<? super B> lsb6 = new ArrayList<D>();//not compile

now we put some objects:

Object o = new Object();
Integer i = new Integer(3);
A a = new A();
B b = new B();
C c = new C();
D d = new D();

I will try to add these objects to the List:

List<? super B> lsb = new ArrayList<A>();
lsb.add(o);//not compile
lsb.add(i);//not compile 
lsb.add(a);//not compile
lsb.add(b);
lsb.add(c);
lsb.add(d);

Question:

Why, when I define the link for List<? super B>, can I use new ArrayList<>();, which can have the element types B, A, Object (I expected this), but when I add elements to this list I can add only objects with types B, C, D ?

+3
source share
2 answers

Clarified beautifully here @ JavaRanch FAQ .

+5

A List<? super B> List, . , B, A Object.

List<B>.

List<B>, A.

, :

String[] x = new String[10];
Object[] x2 = x;
x2[0] = 123; // not a String, compiles, but crashes at run-time
+4

Source: https://habr.com/ru/post/1725930/


All Articles