迭代时允许对Map进行哪些基本操作? [英] What basic operations on a Map are permitted while iterating over it?

查看:149
本文介绍了迭代时允许对Map进行哪些基本操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在迭代Java中的Map ...我不清楚在迭代过程中我可以对Map进行什么操作。我想我对Javadoc中的这个警告大多感到困惑,因为Iterator接口删除方法:

Say I am iterating over a Map in Java... I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in the Javadoc for the Iterator interface remove method:


[...]一个行为如果通过调用此方法以外的任何方式修改基础集合,则未指定迭代器。

[...] 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集合时,我可以:

I know for sure that I can invoke the remove method without any issues. But while iterating over the Map collection, can I:


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

  1. Change the value associated with a key with the Map class put method (put with an existing key)?

使用Map类put方法添加新条目(使用新密钥放置)?

Add a new entry with the Map class put method (put with a new key)?

使用Map类删除方法删除条目?

Remove an entry with the Map class remove method?

我的猜测是我可以安全地做#1(放到现有的钥匙),但不安全做#2或#3。

My guess is that I can probably safely do #1 (put to an existing key) but not safely do #2 or #3.

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

Thanks in advance for any clarification on this.

推荐答案

您可以使用 Iterator.remove(),如果使用一个entrySet迭代器(Map.Entry的)你可以使用 Map.Entry.setValue()。其他所有投注都没有 - 您不应该直接更改地图,而某些地图将是
不允许上述方法中的任何一个或两个。

You can use Iterator.remove(), and if using an entrySet iterator (of Map.Entry's) you can use Map.Entry.setValue(). Anything else and all bets are off - you should not change the map directly, and some maps will not permit either or both of the aforementioned methods.

具体,你的(1),(2)和(3)允许。

Specifically, your (1), (2) and (3) are not permitted.

可能会离开通过 Map 对象设置现有密钥的值,但是 Set.iterator()文档特别排除了它和它将是特定于实现的:

You might get away with setting an existing key's value through the Map object, but the Set.iterator() documentation specifically precludes that and it will be implementation specific:


如果在对集合进行迭代时修改了映射(除非通过迭代器自己的remove操作,或者通过对迭代器返回的映射条目的setValue操作,迭代的结果是未定义的。 (重点补充)

这篇关于迭代时允许对Map进行哪些基本操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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