Is there something better than a For loop in Java for iterating neatly through a collection?
I've been spoiled by C# with 开发者_如何学JAVAthe Foreach. Is there something like this for Java?
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.
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.
精彩评论