我有一个包含整数的 TreeSet。我循环遍历这个集合并一一“消耗”整数。在每个循环中,我需要将剩余的未消耗的整数加 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
,我认为这是由于我修改了循环头中使用的集合引起的。
如何在循环时修改集合的内容?我尝试以几种不同的方式来回复制集合,但代码不断失败并出现相同的错误消息。我不能在循环时修改集合,但是修改集合是此循环的全部目的。//
最佳答案
除非允许的规定,否则您不能在迭代期间修改数据结构。对于迭代器来说,这只是 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);
}
关于java - 不允许在 for 循环中操作 TreeSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65251827/