Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a collection have multiple iterators in Java?

Is it possible to have multiple iterators in a single collection and have each keep track independently? This is assuming no deletes or inserts after the iterators were assigned.

like image 429
cp. Avatar asked Mar 15 '11 17:03

cp.


People also ask

Can we use two iterators in Java?

Basically, you can't use two Iterators on the same Vector simultaneously. Not for Vector, ArrayList, LinkedList, or other common collections.

How many iterators are there in Java?

Iterators are used to traverse through the Java collections. There are three types of iterators.

What is iterator in Java collection?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java.util package.


2 Answers

Yes.

Sometimes it's really annoying that answers have to be 30 characters.

like image 165
ColinD Avatar answered Sep 28 '22 01:09

ColinD


Yes, it is possible. That's one reason they are iterators, and not simply methods of the collection.

For example List iterators (defined in AbstractList) hold an int to the current index (for the iterator). If you create multiple iterators and call next() a different number of times, each of them will have its int cursor with a different value.

like image 36
Bozho Avatar answered Sep 28 '22 02:09

Bozho