Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding to generic collection

 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
The following code compiles:
List <? super Integer> al = new ArrayList<Number>(); //line 1
al.add(12); //line 2
al.add(12+ 13); //line 3

while the following code does not compile:
List <? extends Number> al = new ArrayList<Integer>(); //line 1
al.add(12); //line 2
al.add(12+ 13); //line 3

Can anyone explain why?
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When using the wild card alone or with 'extends', you cant add to the collection, its intended for read only. But with 'super' its ok, can add.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because when you have (first example) a
List <? super Integer> al = new ArrayList<Number>();

Then the list "al" contains only numbers.
This is type safe, you can only add Integers to this list, and what you get out of the list are always Objects.
And because you can say
Object o = new Integer(3);
this should work.

By the way:
List <? super Integer> al2 = new ArrayList<Object>();
would work just the same.


But when you have (second example)
List <? extends Number> al = new ArrayList<Integer>();

You may think in the first place that
add(3);

would be fine, but what you add to this list would always be of type Number, so you also could try to
add(3.0);

And further you also can rereference "al" to another List:
al = new ArrayList<Double>();
this is allowed, and therefore it is not allowed to add anything (except null) to this kinds of lists.



Yours,
Bu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic