java - 遍历 Map 时允许对 Map 执行哪些基本操作?

标签 java iterator

假设我正在用 Java 迭代一个 map ...我不清楚在迭代它的过程中我可以对该 map 做什么。我想我对 Iterator 接口(interface) remove 方法的 Javadoc 中的这个警告感到很困惑:

[...] 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.

我确信我可以毫无问题地调用 remove 方法。但是在遍历 Map 集合时,我可以:

  1. 使用 Map 类的 put 方法更改与键关联的值(使用现有键放置)?

  2. 用 Map 类的 put 方法添加一个新条目(用新键 put)?

  3. 使用 Map 类的 remove 方法删除条目?

我的猜测是我可能可以安全地执行#1(放入现有 key )但不能安全地执行#2 或#3。

提前感谢您对此的任何澄清。

最佳答案

您可以使用 Iterator.remove(),如果使用 entrySet 迭代器(Map.Entry 的),您可以使用 Map.Entry.setValue()。任何其他事情,所有的赌注都没有了——你不应该直接改变 map ,有些 map 会 不允许使用上述任何一种或两种方法。

具体来说,不允许您的 (1)、(2) 和 (3)。

可能通过 Map 对象设置现有键的值,但 Set.iterator() 文档明确排除了这种情况它将特定于实现:

If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. (emphasis added)

关于java - 遍历 Map 时允许对 Map 执行哪些基本操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/490557/

相关文章:

java - 在子类继承的 AbstractMap.SimpleEntry 上实现新接口(interface)?

java - 将数据加载到表中

c++ - 多重删除

java - 使用迭代器进行 "downward"次迭代的优雅方式

c++ - 使用自定义增量迭代二维 vector

java - 如何在 apache Camel (spring) 中测试路由

java - 单击主页/后退按钮时的 android 进度条

java - 如何在忽略转义逗号的同时拆分逗号分隔的字符串?

c++ - 函数模板只接受双向迭代器或指针

javascript - 在 ECMAScript 6 草案中,使用 StopIteration 异常来表示迭代结束的基本原理是什么?