my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Adding to generic collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Adding to generic collection" Watch "Adding to generic collection" New topic

Adding to generic collection

Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
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

Joined: Apr 22, 2006
Posts: 424
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

Joined: Aug 25, 2006
Posts: 1274
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

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

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.


all events occur in real time
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Adding to generic collection
It's not a secret anymore!