简体   繁体   中英

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. 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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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