When I use JDK5 like below
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : list) {
//cannot check if already reached last item
}
on the other hand if I just use an Iterator
ArrayList<Integer> list = new ArrayList<Integer>();
for (Iterator i = list.iterator(); i.hasNext();) {
//i can check whether this is last item
if(i.hasNextItem()){
}
}
How can I check if I've already reached last item with for (Integer i : list) {
The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:
This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).
Another way, you can use a pass-through object to capture the last value and then do something with it:
One way to do that is to use a counter:
Edit
Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a
for
loop or theiterator
, as everything you win when using the Java5 syntax will be lost in the loop itself...or
Sometimes it's just better to use an iterator.
(Allegedly, "85%" of the requests for an index in the posh for loop is for implementing a
String
join method (which you can easily do without).)