Re: listing dirs in current webapp...
maya wrote:
(have never seen this construction..
for (File child:children) {
couldn't use it in the end b/c needed standard 'i' var that's
declared/init'd in loops.. but curious anyway..
This form of the 'for' loop was introduced in Java 5 (1.5), and is called the
'for-each' loop, or the 'enhanced-for' loop.
<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html>
From the JLS
<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2>
The enhanced for statement has the form:
EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement
The Expression must either have type Iterable
or else it must be of an array type (?10.1),
or a compile-time error occurs.
In your example, 'children' is the Expression, and is either an array,
File [] children;
or some Iterable such as a List <File>.
The 'for-each' loop is shorthand for, and works pretty near the same as, the
equivalent "classic" 'for' loop (where 'children' is an Iterable <File>):
for ( Iterator <File> iter = children.iterator(); iter.hasNext(); )
{
File child = iter.next();
doSomethingWith( child );
}
For situations where, as you say, one needs the index, the 'for-each' isn't
the right idiom. It is merely a shortcut around the Iterator, suitable when
an Iterator would have been involved. The 'for-each' focuses on the value
returned at each iteration, the classic 'for' on position within the overall
collection. Depending on which semantics suit the algorithm better, one
chooses the corresponding idiom.
Classic 'for' also has some lovely and esoteric powers far beyond the ken of
'for-each'. My favorite is
for ( ; ; ) { ... }
<http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.1>
--
Lew