List<? extends Integer> list = new ArrayList<Integer>();
            for (Integer element : list) { 
                System.out.println(element);

List<? super Integer> list = new ArrayList<Integer>();
            for (Integer element : list) { 
                System.out.println(element); 

For the first three lines as Case 1 using extends it compiles fine. But for Case 2 of next three lines, it says incompatible types. Found Object, required Integer. My confusion is ? extends Integer being anything that is an Integer or sub of it works.

But why in Case 2 where ? super Integer means anything that is an Integer or a superclass of Integer doesn't work when it's elements ar being given to an Integer element in the for loop??

Case 1 every element is an Integer or a subclass of Integer. All subclasses of Integer are Integers (can be cast to Integer), so the implicit cast to Integer is OK
Case 2 every element is an Integer or a superclass of Integer. Not all superclasses of Integer are Integers (eg Object is not a kind of Integer), so the implicit cast is not valid.

Ok so in general the first line of both case which is instantiation says what compatible elements can be added into the list? if that's the case why is this code below wrong:

NavigableSet<? super String> set = new TreeSet<String>();
set.add(new Object());

Compiler says cannot find symbol: method add(java.lang.Object)
Isn't <? super String> should allow addition of Object since it is a superclass of String?

Likewise for

NavigableSet<?> set = new TreeSet<Object>();
            set.add(new Object());

Saying same error as one on previous post.

Why I asked that question was because I noticed with super wild card, that whatever is on the RHS(right hand side) of super keyword is only accepted or it's sub class.

For e.g.

NavigableSet<? super Object> set = new TreeSet<Object>();
            set.add(new Object()); 
            set.add(new String("Hello"));

is accepting both Object and String following my assumption of anything on RHS of super or it's subclass.

So going back to my very first post,

List<? super Integer> list = new ArrayList<Integer>();
            for (Integer element : list) { 
                System.out.println(element); 

this should accept and Integer object and hence in the for loop when list varible is assigned to another Integer wrraper itself, why complains of incompatible types ?? :( :(

Because it will also accept objects from Integer's superclass(es), and they cannot be assigned to an Integer variable

Thanks again james!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.