Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: for :each style question Date: Wed, 30 Nov 2011 21:35:59 -0500 Organization: A noiseless patient Spider Lines: 47 Message-ID: References: <30fdd7tlkkejm29ufduhc9nnfk7uu3c6h0@4ax.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 1 Dec 2011 02:36:03 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="HSlJAUb3pGXi3i7ZL/HoAw"; logging-data="8005"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/gku6vcTjmcE/L9ICK5DG/" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20111105 Thunderbird/8.0 In-Reply-To: <30fdd7tlkkejm29ufduhc9nnfk7uu3c6h0@4ax.com> Cancel-Lock: sha1:UaUjvHVSjupcp3ZBZi7vegJkAiQ= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:10393 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