Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java iterators and for-each-loop. any way to access the underlying iterator?

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.

like image 432
Albert Avatar asked Oct 15 '10 12:10

Albert


People also ask

Can you use a for-each loop on an iterator Java?

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 .

Which is better for-each loop or iterator?

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.

How do you access elements with iterators?

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.

Is just like iterator except it allows us to access the collection?

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.


1 Answers

No, the whole point of the for-each-loop is to abstract away the underlying iterator.

If you need it, you must declare it.

like image 116
sleske Avatar answered Sep 21 '22 00:09

sleske