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 Beginning Java and the fly likes for(int i:objList) i don understand how this works? 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 » Java » Beginning Java
Bookmark "for(int i:objList) i don understand how this works?" Watch "for(int i:objList) i don understand how this works?" New topic
Author

for(int i:objList) i don understand how this works?

Anjali Raman
Ranch Hand

Joined: Nov 28, 2007
Posts: 57
Hi,
in our project in many places they have used for loops like -



where objList is an List. I havent been able to understand how this is implemented as I somehow prefer using the traditional "for" loop. So can someone please throw some light on this enhanced for loop as they call it.
Vivek Singh
Ranch Hand

Joined: Oct 27, 2009
Posts: 92

***now first time the first object of objList is assigned to i (autoboxing is done) i=4 , then i=6..till end
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10170
    
    8

More information on the enhanced for loop can be found here http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

The above is shorthand for the following:
For arrays it is similar:
Now in your example, objList is probably a List<Integer>, which means that besides this for-each loop, it is also using auto unboxing to convert Integer objects into ints implicitly.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1369
    
    1


This construct was added to the language to make iterating through collections less uglier or more readable. You can use it to iterate over both a collection and an array(as already demonstrated in earlier posts).

Assuming you know how to use a for loop, if you find this new syntax confusing, try reading it as:
"for each integer i in the objList array or iterable do the following.."




[List of FAQs] | [Android FAQ] | [Samuh Varta]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for(int i:objList) i don understand how this works?
 
Similar Threads
Explaining For-Loop
For loop within a for loop
For loop
Java "math" ?
pre and postfix operator in for loop