在 Java 中修改对象时如何迭代它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3517666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:12:39  来源:igfitidea点击:

How can I iterate over an object while modifying it in Java?

javaexceptionhashmapconcurrentmodification

提问by Hristo

Possible Duplicates:
Java: Efficient Equivalent to Removing while Iterating a Collection
Removing items from a collection in java while iterating over it

可能的重复项:
Java:高效等效于在迭代集合时
删除在 Java 中迭代集合时从集合中删除项目

I'm trying to loop through HashMap:

我正在尝试循环HashMap

Map<String, Integer> group0 = new HashMap<String, Integer>();

... and extract every element in group0. This is my approach:

... 并提取group0. 这是我的方法:

// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }
}

The problem here is that each call to assign()will remove elements from group0, thus modifying its size, thus causing the following error:

这里的问题是每次调用assign()都会从 中删除元素group0,从而修改其大小,从而导致以下错误:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832)
    at liarliar$Bipartite.bipartition(liarliar.java:463)
    at liarliar$Bipartite.readFile(liarliar.java:216)
    at liarliar.main(liarliar.java:483)

So... how can I loop through the elements in group0while it's dynamically changing?

那么...如何在元素group0动态变化时循环遍历元素?

回答by Sean Patrick Floyd

Others have mentioned the correct solution without actually spelling it out. So here it is:

其他人提到了正确的解决方案,但实际上并未详细说明。所以这里是:

Iterator<Map.Entry<String, Integer>> iterator = 
    group0.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());

    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }

    // I don't know under which conditions you want to remove the entry
    // but here's how you do it
    iterator.remove();
}

Also, if you want to safely change the map in your assign function, you need to pass in the iterator (of which you can only use the remove function and only once) or the entry to change the value.

此外,如果您想安全地更改分配函数中的映射,则需要传入迭代器(其中您只能使用 remove 函数并且只能使用一次)或更改值的条目。

回答by Bill K

回答by CurtainDog

In your particular case I would not modify the structure of the HashMap but merely null the value you want to remove. Then if you end up visiting a null value just skip it.

在您的特定情况下,我不会修改 HashMap 的结构,而只会将您要删除的值设为 null。然后,如果您最终访问一个空值,只需跳过它。

In the general case I prefer to use a Stack for things like this because they're particularly easy to visualise and so I tend to have less issues with border conditions (just keeping popping 'till empty).

在一般情况下,我更喜欢使用 Stack 来处理这样的事情,因为它们特别容易可视化,所以我倾向于减少边界条件的问题(只是保持弹出直到空)。

回答by Affe

You need to use the actual iterator and its remove method if you want to modify the collection while looping over it. There isn't really any way to do it with the foreach construct.

如果要在循环遍历集合时修改集合,则需要使用实际的迭代器及其 remove 方法。使用 foreach 构造实际上没有任何方法可以做到这一点。

If you're trying to remove multiple entries in one iteration, you'll need to loop over something that's not backed by the map.

如果您尝试在一次迭代中删除多个条目,则需要循环遍历不受地图支持的内容。

Set<String> keys = new HashSet<String>(group0.keySet());
for (String key : keys) {
  if (group0.containsKey(key)) {
    Integer value = group0.get(key);
    //your stuff 
  }
}

回答by fastcodejava

In this case, how can assignmodify group0? More details are needed. Typically you cannot modify a collection while iterating over it. You modify through the Iteratorinterface.

在这种情况下,如何assign修改group0?需要更多细节。通常,您不能在迭代集合时修改它。您可以通过Iterator接口进行修改。