【发布时间】:2022-01-20 22:45:34
【问题描述】:
是否可以在同一个列表的两个迭代器之间进行迭代并删除嵌套迭代器中的一个项目?
版本 1(不起作用):
var i = all.iterator();
while (i.hasNext()) {
var a = i.next();
var j = all.iterator();
while (j.hasNext()) {
var b = j.next();
if (!a.shouldBRemoved(b)) {
a.setDuplicates(a.getDuplicates + 1);
// I want to remove the element on the fly
// because on each iteration the iterated elements will have a decreased size and will iterate faster (because of fewer elements)
// However: this does NOT work because of ConcurrentModificationException:
j.remove();
}
}
}
我得到一个java.util.ConcurrentModificationException,因为我在同一个迭代器中修改了一个元素..
我可以通过使用另一个列表removableItems 来解决这个问题,并将这些项目放入其中:
第 2 版(有效):
for (var a : all) {
for (var b : all) {
if (!a.shouldBRemoved(b)) {
a.setDuplicates(a.getDuplicates + 1);
// this works,
// however I must use an additation list to keep track of the items to be removed
// it's also not more performant than removing the elements on the fly
// because on each iteration the iterated elements has the same size
removableItems.add(b);
}
}
}
all.removeAll(removableItems);
有没有办法解决这个问题不需要需要中间列表removableItems?我想即时删除元素。
【问题讨论】:
-
我不确定你想问什么。
-
没有任何代码 sn-ps 证明需要嵌套循环/迭代。如果方法
a.shouldBeRemoved仅在a上调用而不使用/传递b,则可以将其从外部迭代器中删除。 -
@AlexRudenko 好点。我确实忘记将
b传递给a.shouldBeRemoved()。我编辑了上面的代码。 -
在使用嵌套迭代器进行迭代时,您还应该检查
a == b是否相等。你能澄清哪些项目应该被删除(重复?)以及哪些值应该保留在all中?
标签: java collections