participate


Generics - Unboxing items in enhanced for loop
<<   Back to Forum  |   Give us Feedback
This topic has 3 replies on 1 page.
subterfusion
Posts:11
Registered: 8/12/02
Unboxing items in enhanced for loop   
Aug 18, 2003 8:57 AM

 
Consider the following code:

Collection<Integer> c = new ArrayList<Integer>();
c.add(1);
c.add(new Integer(2));
c.add(3);
 
for(int i : c) {
    // do something
}


Shouldn't unboxing allow me to treat each item in the Collection as a primitive int rather than the Object version?
 
gafter
Posts:669
Registered: 6/25/98
Re: Unboxing items in enhanced for loop   
Aug 18, 2003 2:46 PM (reply 1 of 3)  (In reply to original post )

 
Shouldn't unboxing allow me to treat each item in the
Collection as a primitive int rather than the Object
version?

Perhaps, but the current prototype implements boxing/unboxing
as an argument conversion only.
 
enotecha
Posts:1
Registered: 9/20/00
Re: Unboxing items in enhanced for loop   
Mar 1, 2004 7:27 AM (reply 2 of 3)  (In reply to #1 )

 
Actually that is not true. This code works fine which means that return values are unboxed:

Collection<Integer> foo = new ArrayList<Integer>();
foo.add(3);

int i = foo.get(0);

This is a bug. I'm going to open a ticket today if I have time and the bug database application doesn't crash again.
 
afreije
Posts:146
Registered: 11/10/98
Re: Unboxing items in enhanced for loop   
Mar 1, 2004 3:05 PM (reply 3 of 3)  (In reply to #1 )

 
please note that
for (int i: s) {
   ...
}

is not really safe because iterable s can contain null values, so you should know for sure that s contains no null values if you use this construct.
If you are not sure, ou should use something like
for (Integer i: s) if (i != null) {
   ...
}
 
This topic has 3 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 56
  • Guests : 138

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums