Reputation: 23
HashSet<String> set = new HashSet<String>();
set.add("test1");
Iterator<String> it = set.iterator();
while(it.hasNext()){
it.next();
set.add("sf");
it.remove();
}
Throws me the exception:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(Unknown Source)
If I delete the set.add("sf");
it works obviously.
But why can't I add something to my HashSet while using the iterator?
Upvotes: 0
Views: 2024
Reputation: 393831
No, the Iterator
interface doesn't support adding elements to the Collection
during iteration.
If you were using a List
instead of Set
, you could have used a ListIterator
that does support adding elements during iteration.
This is specified in the Javadoc of Iterator
's remove()
method:
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
The reason add()
cannot be supported by Iterator
s over an arbitrary Collection
is that some collections, such as HashSet
which you are using, don't have an ordering of their elements. An element added while iterating over a HashSet
may be added before or after the current position of the Iterator
(depending on its hashCode
), so the iterator's behavior after adding the element will be unpredictable.
Upvotes: 1
Reputation: 2626
Iterator does not support add while iterating .In collection iterator use expectedModCount to check if it is modified by other.When you do some add using set reference modCount value increases and expectedModCount not changed cause exception.
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
public interface Iterator {
boolean hasNext();
E next();
void remove();
}
Upvotes: 1