Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Alternative to iterator.hasNext() if using for-each to loop over a collection

I'm trying to replace an iterator-based loop over a Java list with a for-each statement, but the code uses at some point iterator.hasNext() to check if it reached the last element in the list.

Is there something similar for the for-each alternative?

for (Object current : objectList) {
   if (last-element) 
      do-something-special
}
like image 782
Dan Burzo Avatar asked Nov 23 '09 12:11

Dan Burzo


2 Answers

for-each is just syntactic sugar for iterator version and if you check compiled bytecode, then you'll notice that compilator actually change it into iterator version.

With a for-each form you can't check whether you'll have more elements or not. Just stay with explicit iterator use if you need that feature.

like image 97
Mirek Pluta Avatar answered Oct 09 '22 13:10

Mirek Pluta


In addition to Luno's answer:

Iterator<MyClass> it = myCollection.iterator();
while(it.hasNext()) {
  MyClass myClass = it.next():
  // do something with myClass
}

translates to:

for (MyClass myClass:myCollection) {
  // do something with myClass
}
like image 23
Andreas Dolk Avatar answered Oct 09 '22 11:10

Andreas Dolk