」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在迭代過程中修改陣列列表時,如何避免contrentModification Exception?

在迭代過程中修改陣列列表時,如何避免contrentModification Exception?

發佈於2025-03-22
瀏覽:534

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

ConcurrentModificationException while Modifying an ArrayList During Iteration

The reported exception is a ConcurrentModificationException, originating from the attempt to modify an ArrayList, mElements, while iterating over it.

Inside an OnTouchEvent處理程序,使用迭代器對融合的融合有一個循環迭代以檢查特定條件:

進行修改(通過添加新元素)。完成迭代:
for (Iterator it = mElements.iterator(); it.hasNext();){
    Element element = it.next();

    // Check element's position and other conditions...

    if(element.cFlag){
        mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY)); // ConcurrentModificationException occurs here
        element.cFlag = false;
    }
}

Alternative Approach:

Another approach is to use an enhanced for-each loop, which iterates over a copy of the list, preventing ConcurrentModificationException:

for (Element element : mElements) { //檢查元素的位置和其他條件... 如果(element.cflag){ MELEMENTS.ADD(新元素(“ crack”,getResources(),(int)touchx,(int)touchy)); //沒有conturrentModificationException element.cflag = false; } }

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3