I very much like the for-each-loop construction (for(T e : iterable)
) in Java which works on any Iterable<T>
because it makes in many cases very easy to read and to write code.
I wonder though if there is any way that I can access the underlying iterator from such a loop. This can be mandatory if I want to use the remove()
from the iterator.
Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove .
In for-each loop, we can't modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. Modifying a collection simply means removing an element or changing content of an item stored in the collection.
By using this iterator object, you can access each element in the collection, one element at a time. Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
As explained, a list iterator gives you the ability to access the collection in either the forward or backward direction and lets you modify an element. Otherwise, ListIterator is used just like Iterator.
No, the whole point of the for-each-loop is to abstract away the underlying iterator.
If you need it, you must declare it.
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