I'm using Java 6.
Suppose I had a bunch of cats to feed, and suppose myCats is sorted.
for (Cat cat : myCats) {
feedDryFood(cat);
//if this is the last cat (my favorite), give her a tuna
if (...)
alsoFeedTuna(cat);
}
and I wanted to treat my last cat specially.
Is there a way to do this elegantly inside the loop? The only way I can think of is counting them.
Stepping back a little bit for a wider picture, is there any programming language that supports this little feature in a for-each loop?
If you need to do this, the best approach might be to use an Iterator. Other than that, you have to count. The iterator has a
hasNext()
method that you can use to determine if you are on the last item of your iterations.
EDIT -- To increase readability you can do something like the following within the Iterator based loop (psuedo):
Cat cat = iter.next();
feedDryFood(cat);
boolean shouldGetTuna = !iter.hasNext();
if (shouldGetTuna)
alsoFeedTuna(cat)
that is fairly self-documenting code via clever use of variable names.