不允许在for循环中操作treeset

41ik7eoe  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(544)

我有一个包含整数的树集。我在这个集合中循环,一个接一个地“消耗”整数。在每个循环中,我需要将剩余的未求和整数加1。
例如,我从一个有四个值的集合开始: 2, 3, 5, 8 . 在我消费的第一个循环之后 2 结果应该是包含此内容的集合 4, 6 , 9 . 第二圈之后,在哪里 4 是被消耗的,应该是 7, 10 等等。
我不需要在消耗完最后一个值之后再增加一步(但是如果是的话也没关系)。
如果消耗的值仍在集合中,则是可以的,而不管它们是处于原始值还是增加的值。换句话说,在第二个循环之后,如果集合包含 2, 3, 7, 10 或者 2, 4, 7, 10 或者只是 7, 10 . (循环结束后,该集合将被丢弃)
这是我的密码

  1. for (Integer i : positionSet) {
  2. TreeSet <Integer> tmpSet = new TreeSet<>();
  3. //use i for something
  4. //positionSet.remove(i); //I tried with this both on and off, but it made no difference
  5. for (Integer j : positionSet) {
  6. tmpSet.add(j + 1);
  7. }
  8. positionSet.clear();
  9. positionSet.addAll(tmpSet);
  10. }

它在第二轮的时候撞了个正着 java.util.ConcurrentModificationException ,我认为这是由于修改循环头中使用的集合引起的。
如何在循环时修改集合的内容?我试着用几种不同的方法来回复制set,但代码总是失败,并显示相同的错误消息。我不能在循环时修改集合,但是修改集合是这个循环的全部目的//

0lvr5msh

0lvr5msh1#

除了允许的规定外,您不能在迭代期间修改数据结构。对于迭代器,这只是 Iterator.remove() ,但for each没有这样的规定,也不能影响其他元素。
最好是创建一个独立于数据结构的while循环:

  1. while (!positionSet.isEmpty()) {
  2. Integer i = <take one element out of positionSet somehow>;
  3. //positionSet.remove(i); //remove if the previous line didn't already remove it
  4. //use i for something
  5. TreeSet <Integer> tmpSet = new TreeSet<>();
  6. for (Integer j : positionSet) {
  7. tmpSet.add(j + 1);
  8. }
  9. positionSet.clear();
  10. positionSet.addAll(tmpSet);
  11. }

相关问题