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

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

Using iterator in loop without causing any exceptions

问题

我使用了迭代器类来解决一个问题。
我认为 HashSet 的 iterator() 方法会返回其迭代器的集合。
但是每当我运行这段代码(特别是第5行),就会出现 ConcurrentModificationException,尽管我已经检查过迭代器是否有下一个元素。

抱歉我的英文不好,但我真的想弄清楚我的代码有什么问题,并修复这些问题。

  1. for (int i = 0; i < N; i++) {
  2. int input = scan.nextInt();
  3. iterator = set.iterator();
  4. while (iterator.hasNext()) {
  5. int num = iterator.next();
  6. if (!set.contains(num + input)) set.add(num + input);
  7. }
  8. }
英文:

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.

  1. for (int i = 0; i &lt; N; i++) {
  2. int input = scan.nextInt();
  3. iterator = set.iterator();
  4. while (iterator.hasNext()) {
  5. int num = iterator.next();
  6. if (!set.contains(num + input)) set.add(num + input);
  7. }
  8. }

答案1

得分: 0

将添加操作存储在本地的 Set/List 中。

在整体迭代之后,只需将它们全部添加。

  1. Set toAdd = new HashSet();
  2. for (int i = 0; i < N; i++) {
  3. int input = scan.nextInt();
  4. iterator = set.iterator();
  5. toAdd.clear();
  6. while (iterator.hasNext()) {
  7. int num = iterator.next();
  8. if (!set.contains(num + input)) toAdd.add(num + input);
  9. }
  10. set.addAll(toAdd);
  11. }
英文:

Store the Adds in a local Set/List.

after iterating overall, just add them all

  1. Set toAdd = new HashSet();
  2. for (int i = 0; i &lt; N; i++) {
  3. int input = scan.nextInt();
  4. iterator = set.iterator();
  5. toAdd.clear();
  6. while (iterator.hasNext()) {
  7. int num = iterator.next();
  8. if (!set.contains(num + input)) toAdd.add(num + input);
  9. }
  10. set.addAll(toAdd);
  11. }

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:

确定