Adding items to a HashMap while looping with Itera

2019-05-31 01:40发布

问题:

I have a program that loops through a HashMap using an Iterator, and inside the loop, I'm adding to the HashMap - which is causing a ConcurrentModificationException. I've seen that ListIterator has an add() function that handles this, but Iterator does not.

The HashMap is set up like this -

HashMap<Pair<Integer, Integer>, Object>

And the iterator like this -

Iterator<Entry<Pair<Integer, Integer>, Object>> iter;

With Object (not the real name) being a class from my program. Does anybody know how I can go about adding to the iterator while I'm looping or any other options?

回答1:

Loop through a copy of the map instead, and add to the original map. The entry set of a map is a view of the Map's key value pairs, and does not support addition though you can remove items.

Alternatively you can add elements to a new map while iterating and then use putAll() afterwards ... come to think of it, that is probably more efficient.