7.6 Determining List Position and Variable Value
for/in, more than anything else, is
about convenience. However, with
that convenience comes a degree of lost flexibility. One such example is
the inability to determine the position in a list that the for/in construct
resides at. As your code executes within the for/in loop, there is no way
to access the position in the list. Additionally, the list variable itself isn't
accessible, making its access equally impossible.
7.6.1 How do I do that?
In short, you don't. Sometimes it's just as important to realize what you
can't do as it is to learn what you can.A common iteration technique is to use the loop variable, especially if it's
numerical, in the loop body itself:
This is perfectly legitimate, and really useful if you're performing some
List<String> wordList = new LinkedList<String>( );
for (int i=0; i<args.length; i++) {
wordList.add("word " + (i+1) + ": '" + args[i] + "'");
}
sort of count. However, it's impossible to access the iterator in a for/in
loop, as that's kept internal (and not even generated until compilation
takes place). In this case, you're out of luck. You can use for/in to display
the results of a situation like this, but not to make the assignment
itself:
This is hardly a severe limitation, but it's one you should be aware of.Another common usage of lists is String concatenation,
public void determineListPosition(PrintStream out, String[] args)
throws IOException {
List<String> wordList = new LinkedList<String>( );
for (int i=0; i<args.length; i++) {
wordList.add("word " + (i+1) + ": '" + args[i] + "'");
}
for (String word : wordList) {
out.println(word);
}
}
and that illustrates
another of the for/in limitations. It's common in String concatenation
to add separators between all but the last of a set of words, such
as when printing a list. This separator is often a comma or perhaps a
space:
Here, all but the last word in the list has a comma appended to it, while
StringBuffer longList = new StringBuffer( );
for (int i = 0, len=wordList.size( ); i < len; i++) {
if (i < (len-1)) {
longList.append(wordList.get(i))
.append(", ");
} else {
longList.append(wordList.get(i));
}
}
out.println(longList);
the last one is appended without a comma. This makes for a nice list output.
However, this rather simple task is impossible with for/in, because
the variable that is used to do all the work, i, is inaccessible in a for/in
loop. Again, a fairly minor inconvenience, but it's certainly not time to
retire our old friend for just yet.