tags:

views:

131

answers:

2

I've been spoiled by C# with the Foreach. Is there something like this for Java?

+9  A: 

Yes, the enhanced for loop which was introduced in Java 1.5:

List<String> strings = getStringsFromSomewhere();
for (String x : strings)
{
    System.out.println(x);
}

It works on arrays and anything implementing Iterable<T> (or the raw Iterable type).

See section 14.14.2 of the JLS for more details.

Jon Skeet
Is there anything you DON'T know? :P Thanks, and BTW great C# book.
Sergio Tapia
@Sergio: Well I write Java during the day, so this isn't a biggie for me :) Glad you're enjoying the book.
Jon Skeet
+5  A: 

Java has for...each loops also - in fact, most languages do!

You can use a for...each loop with syntax like this:

for( dataType value : collection ) { /code/ }

You can find more information, as well as code examples and demo programs, at Java's online documentation.

Alex Zylman
To be fair, Java didn't have the foreach syntax for some time (introduced Java 5, I think?)
Brian S