在循环中使用迭代器而不引发任何异常。

huangapple go评论135阅读模式
英文:

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 &lt; 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 &lt; 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);
}

huangapple
  • 本文由 发表于 2020年8月19日 13:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63480616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定