> Hello there!
>
[quoted text clipped - 17 lines]
> So my question is: how can I catch the first/last item, without roll
> the code back to the old iterator-style of loop.
There are ways of doing each, but I think the result would be messier
than the iterator-style loop. Iterator based loops are not deprecated,
and there is absolutely nothing wrong with using them. The new forms are
just shorthand for the very simplest, most routine cases.
Here are a couple of techniques to consider if you really do want to try
to bend the new loop forms beyond what they do naturally:
1. Keep a boolean isFirstIteration, initially true. When it is true, do
the extra first element processing and change it to false.
2. In the iterated statement, assign a copy of the item reference to a
variable declared outside the loop. At the end, it will contain a
reference to the last element, and can be used for additional last
element processing.
Patricia
Hendrik Maryns - 04 Oct 2006 16:25 GMT
Patricia Shanahan schreef:
>> Hello there!
>>
[quoted text clipped - 22 lines]
> and there is absolutely nothing wrong with using them. The new forms are
> just shorthand for the very simplest, most routine cases.
How would you catch the last object with an iterator? The first is no
problem, but there is no way to know you’re handling the last one,
except for checking hasNext() inside the loop once more after doing
next(), which isn’t very nice either. So basically, you have to know
the number of elements and count, or use one of those techniques you
described.
H
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
Patricia Shanahan - 04 Oct 2006 20:03 GMT
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
[quoted text clipped - 32 lines]
> the number of elements and count, or use one of those techniques you
> described.
I was dealing with the case of adding special work.
If you need to not do the normal processing for the last element, it
gets a bit more complicated but can still be done. Run one iteration
behind. Keep a "previousItem" reference, initially null. Inside the loop:
if(previousItem != null){
// deal with previousItem object.
}
previousItem = item;
At the end of the loop, previousItem points to the last element, and it
has not yet been processed.
However, I still think that it would be better and simpler to use an
explicit iterator, and check for hasNext().
Patricia