Adding items to a HashMap while looping with Iterator

佐手、 提交于 2019-12-08 03:34:56

问题


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.



来源:https://stackoverflow.com/questions/28798671/adding-items-to-a-hashmap-while-looping-with-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!