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
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With