假设我正在用 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 集合时,我可以:
使用 Map 类的 put 方法更改与键关联的值(使用现有键放置)?
用 Map 类的 put 方法添加一个新条目(用新键 put)?
使用 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/