Re: for :each style question
On 11/30/2011 6:32 PM, Roedy Green wrote:
In a for:each loop, sometimes you want to treat the first and or last
element specially.
The obvious way to handle is to revert to a for int i= loop and check
for special values of i.
You can keep the for:each style if you have a boolean first= true that
you set false to detect the first.
I don't know of an equivalent way to detect the last.
In the olden days I would have handled the first and last cases
outside the loop, with the loop running over the middle elements. You
can't do that with for:each.
What do you consider the best style to deal with this?
I once taught a student whose DO loops (this was FORTRAN) always
iterated from 1 through N, never from 2 through N or 1 through N-1.
Paraphrasing into zero-based Java, he'd write something like
for (int i = 0; i < array.length; ++i) {
if (i == 0) continue;
if (i == array.length - 1) continue;
massage(array[i-1], array[i], array[i+1]);
}
I was unable to break him of this habit, and eventually formed
the opinion that he had learned The One True Way to write a loop,
and Nothing On Earth would persuade him to write it differently.
That's the wrong way to think about a tool.
The for:each form is a convenience, a prepackaged solution to
a common problem. Do not expect it to be the answer for all kinds
of iteration. for:each is Java's feeble imitation of (mapc); don't
push it beyond its built-in limits. There are lots of other looping
forms available; use them when they suit.
(For those who don't know what (mapc) means, see the current
thread "java developers" and give special attention to Patricia
Shanahan's contribution.)
--
Eric Sosman
esosman@ieee-dot-org.invalid