英文:
Using iterator in loop without causing any exceptions
问题
我使用了迭代器类来解决一个问题。
我认为 HashSet 的 iterator() 方法会返回其迭代器的集合。
但是每当我运行这段代码(特别是第5行),就会出现 ConcurrentModificationException,尽管我已经检查过迭代器是否有下一个元素。
抱歉我的英文不好,但我真的想弄清楚我的代码有什么问题,并修复这些问题。
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);
}
}
英文:
I used iterator class to solve a question.
I thought that iterator() method of HashSet returns the collection of its iterator.
But whenever I ran this code(especially the 5th line) it occurs ConcurrentModificationException, even though I've checked the iterator has next elements.
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);
}
}
答案1
得分: 0
将添加操作存储在本地的 Set/List 中。
在整体迭代之后,只需将它们全部添加。
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);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论