簡體   English   中英

Java:從不同的ArrayLists同時刪除兩個對象

[英]Java: removing two objects simultaniously from different ArrayLists

我有對象Bullet,我同時將它們添加到兩個ArrayList中,下面簡要介紹了這些列表。 完成某些操作后,我希望從兩個列表中刪除一個項目符號。 這種方法正確嗎? 我不斷收到錯誤:java.util.ConcurrentModificationException

或者,您是否可以想到以比ArrayList更好的解決方案來以這種方式處理對象?

    //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;

                }
            }
        }
    }

}

編輯:問題的根源是我在列表之一上使用了一個迭代器,恰好同時在另一個地方,因此出現了錯誤。 對於可更新列表,此代碼工作正常。

發生ConcurrentModificationException的原因是,您試圖從Iterator中刪除項目符號,而您同時也在for循環中進行迭代; java不喜歡您執行此操作,並且會拋出異常。

要解決此問題,您必須遍歷兩個Iterators並分別將其刪除,或者如rdonuk所述,只需使用ArrayList remove()方法,如果您嘗試刪除不在列表中的內容,則不會拋出任何異常。數組列表; 如果刪除了該對象,它將返回true ,否則返回false ,因此您甚至不必首先檢查要刪除的對象是否包含在ArrayList中。

只需使用ArrayList remove方法。

bullets.remove(bullet);

updatable.remove(bullet);

編輯:

移除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();
        }
    }

如您所見,它已經使用ArrayList.remove()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM