This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Adding to generic collection" Watch "Adding to generic collection" New topic
Author

Adding to generic collection

Ganesha Kumar
Ranch Hand

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

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
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


all events occur in real time
 
Don't get me started about those stupid light bulbs.
 
subject: Adding to generic collection
 
Similar Threads
<? super Integer>
generics ? super Integer
doubt in generics
Generics question List with super
Generics