简体   繁体   中英

Java: removing two objects simultaniously from different ArrayLists

I have objects Bullet that I add to two ArrayLists at once, the lists are briefly described below. After certain operations are done I wish to remove a bullet from both lists. Is this approach correct? I keep on getting an error: java.util.ConcurrentModificationException

Alternatively, can you think of a better solution than ArrayList for the purpose of handling objects in this manner?

    //there are ArrayList<Bullet> bullets and ArrayList<Updatable> updatable, in the class

    public void removeBullet(Bullet bullet) {

    for (ListIterator<Bullet> bulletIterator = bullets.listIterator(); bulletIterator.hasNext();) {

        Bullet tempBullet = bulletIterator.next();

        if (tempBullet.equals(bullet)) {

            for (ListIterator<Updatable> updatableIterator = updatable.listIterator(); updatableIterator.hasNext();) {

                Updatable tempUpdatable = updatableIterator.next();
                if (tempUpdatable.equals(bullet)) {

                    updatableIterator.remove();
                    bulletIterator.remove();
                    return;

                }
            }
        }
    }

}

EDIT: The source of problem was that I used an iterator on one of the lists, at exact same time in a different place, hence the error. This code worked fine for the updatable list.

A ConcurrentModificationException happens because you are trying to remove a bullet from an Iterator which you are also simultaneously iterating through in a for loop; java doesn't like when you do that and will throw the exception.

To solve this, you would have to iterate through both Iterators and remove them separately, or, as rdonuk stated, simply use the ArrayList remove() method, which will not throw any exceptions if you try to remove something that isn't in the ArrayList; it will return true if the object was removed, or false otherwise, so you don't even have to check if the object you want to remove is contained in the ArrayList in the first place.

Just use ArrayList remove method.

bullets.remove(bullet);

and

updatable.remove(bullet);

Edit:

remove method of iterator which used by ArrayList :

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

As you see it is already use ArrayList.remove() method.

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