用Iterator循环时将项目添加到HashMap [英] Adding items to a HashMap while looping with Iterator

查看:166
本文介绍了用Iterator循环时将项目添加到HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用迭代器循环访问HashMap的程序,在循环内部,我添加了HashMap - 这导致了ConcurrentModificationException异常。我已经看到ListIterator有一个add()函数来处理这个,但Iterator没有。

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.

HashMap是这样设置的 -

The HashMap is set up like this -

HashMap<Pair<Integer, Integer>, Object>

迭代器像这样 -

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

使用Object(不是真名)是我程序中的一个类。
有人知道如何在循环或任何其他选项时添加到迭代器吗?

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?

推荐答案

改为循环显示地图的副本,然后添加到原始地图中。地图的输入集是Map的键值对的视图,并且不支持添加,但您可以移除项目。

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.

或者,您可以将元素添加到新的然后迭代地图,然后使用 putAll() ...来想一想,这可能更有效率。

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.

这篇关于用Iterator循环时将项目添加到HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆