Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java foreach loop: for (Integer i : list) { ... }

Tags:

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) {

like image 773
cometta Avatar asked Nov 30 '09 09:11

cometta


2 Answers

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

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 the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}
like image 194
Romain Linsolas Avatar answered Sep 20 '22 15:09

Romain Linsolas


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).)

like image 33
Tom Hawtin - tackline Avatar answered Sep 24 '22 15:09

Tom Hawtin - tackline