Re: How to differentiate the first or last item in Java 5 for-each
type of loop?
whmanutd@gmail.com wrote:
Hello there!
I got a code snippet like:
// == start of the code ==
List<String> list = new ArrayList<String>();
...// some code to add String to "list"
for (String item : list) // Java 5 for-each loop
{
// do something.
..
// but also want to something special for the first/last item of the
loop.
}
// == end of the code ==
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