避免使用map.get(key)方法
我有以下代码,但我发现使用 keySet()
迭代 Map 键时从 Map 检索值是一个错误,即使使用 findBugs,我也会收到警告 WMI_WRONG_MAP_ITERATOR
for(String elementId : mapElements.keySet()){
element = mapElements.get(elementId);
doSomething(element);
}
所以为什么这不好,我该如何解决它?
谢谢。
I have the following code but i saw that retrieving values from a Map while iterating over the Map keys with keySet()
is a mistake even with findBugs i get the warning WMI_WRONG_MAP_ITERATOR
for(String elementId : mapElements.keySet()){
element = mapElements.get(elementId);
doSomething(element);
}
so why exactly is this not good and how can i fix it ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您要迭代映射中的所有内容,您也可以这样做:
或者如果您确实不需要键,只需迭代值:
编辑:语法
If you're iterating over everything in a map, you might as well do:
Or if you don't really need the key, just iterate over the values:
EDIT: syntax
在迭代地图本身的同时从地图中检索值不是问题 - 问题在于当您在修改地图的同时迭代它时。就您而言,情况似乎并非如此,因此这本身并不危险。
当您迭代 map 时,您获得的迭代器基于您获得迭代器时所有映射条目的快照。在随后的 midification 中,该迭代器的行为变得未定义。这就是不好的地方。但同样,在您的情况下,这不适用,因为您没有更新地图。
Retrieving values from a map while iterating over the map itself is not an issue - what becomes an issue is when you are modiying the map while simultaneously iterating over it. In your case , this doesnt seem to be the case , so this is itself not dangerous.
When you iterate over a map , the iterator you get is based on a snapshot of all map entries at the time you obtain the iterator. Upon subsequent midification , this iterator's behaviour becomes undefined. This is what is not good. But again, in your case this does not apply because you are not updating the map.
另一点是,如果地图很大,查找每个键的值可能会很昂贵。所以乔恩·斯基特的建议更有效。然而,我承认迭代地图条目集的代码有点笨拙。
Another point is that looking up the value of each key may be expensive if the map is large. So Jon Skeet's suggestion is more efficient. However, I admit the code for iterating over a map's entry set is a bit clumsy.