简体   繁体   English

Java删除一个迭代器,该迭代器删除同一列表中的另一个元素

[英]Java removing an iterator that removes another element in the same list

I have an ArrayList called blocks that is iterated through using an iterator.我有一个名为 blocks 的ArrayList ,它通过使用迭代器进行迭代。 Before i call the .remove() method of the current iterator i must remove another object in the list that is linked to the object being removed.在调用当前迭代器的.remove()方法之前,我必须删除列表中与要删除的对象相关联的另一个对象。 An attempt to do this results in a concurrent modification exception as expected.尝试这样做会导致预期的并发修改异常。 Do you know how i could work around this?你知道我如何解决这个问题吗? Sample code:示例代码:

for (Iterator<Block> iterator = Blocks.iterator(); iterator.hasNext();) {
    Block block = (Block) iterator.next();
    if (block.getX() == x && block.getY() == y) {
        block.remove(); //This removes another block from this list but throws the error
        iterator.remove();
    }
}

If you only need to remove the first match, then the simplest solution would be to iterate through the list to find the first match and save that match in a variable that can be accessed outside of the iterator loop.如果您只需要删除第一个匹配项,那么最简单的解决方案是遍历列表以找到第一个匹配项并将该匹配项保存在可以在迭代器循环之外访问的变量中。 Then just break out of the loop and perform the cleanup (removal) needed然后跳出循环并执行所需的清理(删除)

Block removeMe;
for (Iterator<Block> iterator = Blocks.iterator();  iterator.hasNext();) {
        Block block = (Block) iterator.next();
        if (block.getX() == x && block.getY() == y) {
            removeMe = block; 
            iterator.remove();
            break;
        }
}
removeMe.remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM