"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 반복 중에 Arraylist를 수정할 때 ConcurrentModificationException을 피하는 방법은 무엇입니까?

반복 중에 Arraylist를 수정할 때 ConcurrentModificationException을 피하는 방법은 무엇입니까?

2025-03-22에 게시되었습니다
검색:295

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?

concurrentModificationException 반복 중에 배열리스트를 수정하면서

보고 된 예외는 동시 모성 이식을 수정하려는 시도에서 유래하는 동시 모성 예외입니다.

,

반복기를 사용하여 반복적 인 반복이 있습니다.
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;
    }
}
for (iterator it = melements.iterator (); hasnext ();) { 요소 요소 = it.next (); // 요소의 위치 및 기타 조건을 확인합니다 ... if (element.cflag) { melements.add (새 요소 ( "crack", getResources (), (int) touchx, (int) touchy)); // 동시 대상 외상성이 여기에서 발생합니다 요소 .cflag = false; } }

그러나 반복을 사용하여 반복하는 동안 ArrayList (새로운 요소를 추가하여)를 수정하면 동시 자료를 유발할 수 있습니다. 반복 :

list thingstobeadd = new arraylist (); for (iterator it = melements.iterator (); hasnext ();) { 요소 요소 = it.next (); // 요소의 위치 및 기타 조건을 확인합니다 ... if (element.cflag) { // 새로운 요소를 나중에 추가 할 수있는 별도의 목록에 저장 thingstobeadd.add (새 요소 ( "crack", getResources (), (int) touchx, (int) touchy); 요소 .cflag = false; } } // 임시 목록에서 기본 목록에 모든 요소 추가 melements.addall (thethstobeadd);

대안 접근법 :
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;
    }
}

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

How to Avoid ConcurrentModificationException When Modifying an ArrayList During Iteration?
는 목록의 사본을 반복하여 동시 모음 지출을 방지하는 것입니다. // 요소의 위치 및 기타 조건을 확인합니다 ... if (element.cflag) { melements.add (새 요소 ( "crack", getResources (), (int) touchx, (int) touchy)); // 동의어 modificationException이 없습니다 요소 .cflag = false; } }

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3