Reputation: 2975
Consider the following example,
List<? super Number> list1 = new ArrayList<>();
list1.add(10);
list1.add(10.10);
list1.add(20.20d);
and another list to which i assign list1
List<? super Integer> list = list1;
System.out.println(list.toString());
Now, when i print the list it contains double values also BUT the list is only supposed to hold Integer and anything above Integer.
If the above is fine then shouldn't the following compile as well ?
list.add(30.30);
Upvotes: 1
Views: 171
Reputation: 198014
Everything makes sense if you consider the possible things you could assign to it.
List<? super Number> list1 = new ArrayList<Object>(); // works
List<? super Number> list1 = new ArrayList<Number>(); // works
List<? super Number> list1 = new ArrayList<Integer>(); // doesn't work
Anything that works on the right hand side will accept a Double
.
List<? super Integer> list = new ArrayList<Object>(); // works
List<? super Integer> list = new ArrayList<Number>(); // works
List<? super Integer> list = new ArrayList<Integer>(); // works
Anything that you could assign to list1
you could also assign to list
. So list = list1
works just fine. But not all of the things you could assign to list
will accept a Double
, so it doesn't compile.
Upvotes: 5