简体   繁体   English

在循环中使用迭代器而不会导致任何异常

[英]Using iterator in loop without causing any exceptions

I used iterator class to solve a question.我使用迭代器 class 来解决一个问题。 I thought that iterator() method of HashSet returns the collection of its iterator.我认为 HashSet 的 iterator() 方法返回其迭代器的集合。 But whenever I ran this code(especially the 5th line) it occurs ConcurrentModificationException, even though I've checked the iterator has next elements.但是每当我运行这段代码(尤其是第 5 行)时,它就会发生 ConcurrentModificationException,即使我已经检查过迭代器是否有下一个元素。

Sorry for my bad English, but I really want to find out what's wrong with my code and fix the problems.对不起我的英语不好,但我真的很想找出我的代码有什么问题并解决问题。

for (int i = 0; i < N; i++) {
    int input = scan.nextInt();
    iterator = set.iterator();
    while (iterator.hasNext()) {
        int num = iterator.next();
        if (!set.contains(num + input)) set.add(num + input);
    }
}

Store the Adds in a local Set/List.将添加存储在本地集/列表中。

after iterating overall, just add them all整体迭代后,将它们全部添加

Set toAdd = new HashSet();
for (int i = 0; i < N; i++) {
    int input = scan.nextInt();
    iterator = set.iterator();
    toAdd.clear();
    while (iterator.hasNext()) {
        int num = iterator.next();
        if (!set.contains(num + input)) toAdd.add(num + input);
    }
    set.addAll(toAdd);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM