I've been spoiled by C# with the Foreach. Is there something like this for Java?
views:
131answers:
2
+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
2010-08-03 19:31:03
Is there anything you DON'T know? :P Thanks, and BTW great C# book.
Sergio Tapia
2010-08-03 19:33:01
@Sergio: Well I write Java during the day, so this isn't a biggie for me :) Glad you're enjoying the book.
Jon Skeet
2010-08-03 19:33:34
+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
2010-08-03 19:32:32
To be fair, Java didn't have the foreach syntax for some time (introduced Java 5, I think?)
Brian S
2010-08-03 21:38:15