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

发布于 2024-09-15 08:45:55 字数 1546 浏览 4 评论 0原文

可能的重复:
Java:高效相当于在迭代集合时进行删除
迭代时从 java 集合中删除项目它

我正在尝试循环 HashMap:

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

... 并提取 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);
    }
}

这里的问题是每次调用 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.. .如何在 group0 动态变化时循环遍历它?

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

I'm trying to loop through HashMap:

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

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

// 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:

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 group0 while it's dynamically changing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

剧终人散尽 2024-09-22 08:45:55

其他人提到了正确的解决方案,但没有实际阐明。所以这里是:

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();
}

另外,如果你想安全地改变你的分配函数中的映射,你需要传入迭代器(其中你只能使用删除函数并且只能使用一次)或条目来改变值。

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.

墨小沫ゞ 2024-09-22 08:45:55

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

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

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.

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).

水溶 2024-09-22 08:45:55

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

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

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

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.

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 
  }
}
可爱咩 2024-09-22 08:45:55

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文