不允许在for循环中操作treeset

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

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

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

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

0lvr5msh

0lvr5msh1#

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

while (!positionSet.isEmpty()) {
    Integer i = <take one element out of positionSet somehow>;
    //positionSet.remove(i); //remove if the previous line didn't already remove it

    //use i for something
    TreeSet <Integer> tmpSet = new TreeSet<>();
    for (Integer j : positionSet) {
        tmpSet.add(j + 1);
    }
    positionSet.clear();
    positionSet.addAll(tmpSet);
}

相关问题