Creating a new iterator object every time I cross a list

If I create an Iterator object in any List, should I create a new iterator object every time I cross the list? Or are new items added or removed from the list automatically taken into account by the previously created iterator?

+4
source share
1 answer

Iterator is a one-time utility. Usually you need a new one every time you iterate over a list. However, this is not bad. Iterator have very little state (for an ArrayList , it could just be an int to hold the current index).

If the support list changes between iterator calls, you will get a ConcurrentModificationException from the iterator operation. Adding or removing items should be done using Iterator itself.

+8
source

All Articles