Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialStacy Chambers
1,179 PointsFor Loops for (BlogPost post: mPosts)
Can someone explain this type of for loop or help me find where the track is that explains for loops. I need to review.
1 Answer
gyorgyandorka
13,811 PointsThis is a so-called for each loop.
The syntax in Java looks like this:
for (Type item : someCollectionOfItems) {
// do this stuff in each cycle
}
- the loop will run
n
cycles wheren
is the size ofsomeCollection
-
item
: a newly declared variable which will be assigned to the i-th item in the collection in the i-th cycle of the loop -
someCollection
: the collection (an iterable object) you'd like to iterate through from the first to last element
You can achieve the same with a regular for loop, the difference is that inside the loop body you cannot directy refer to the elements in the collection, only via their indexes:
for (int i = 0; i < anArrayListOfStrings.size(); i++) {
System.out.println(anArrayListOfStrings[i]);
}
// with a for each loop you can use the 'item' variable as an alias for the current item:
for (String item : anArrayListOfStrings) {
System.out.println(item);
}