2016-09-06 2 views
0

내 목록 (정수 목록)에서 원소 중 하나를 제거 할 때 오류가 발생했습니다. 나는 그 요소 여기목록에서 원소를 제거 할 때 자바 오류가 발생했습니다. (정수 목록)

을 제거하는 반복자를 사용하여 내 코드입니다 :

List<List<Integer>> list = new ArrayList<List<Integer>>(); 
.... 
.... 
Iterator<List<Integer>> myListIterator = list.iterator(); 
int ct1 = 0; 
while (myListIterator.hasNext()) { 
    List<Integer> val = myListIterator.next(); // here is the error 
    if(ct1 == val.get(0)) 
     list.remove(val); 
    ct1++; 
} 

가 그리고이 오류 메시지가 있어요 :

이 가
Exception in thread "main" java.util.ConcurrentModificationException 
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source) 
    at java.util.ArrayList$Itr.next(Unknown Source) 

사람이 내 코드를 잘못 알고 있나요을? 감사합니다.

답변

2

이터레이터를 사용하는 동안 요소를 제거했기 때문에. 가능한 해결책은 인덱스가있는 루프를 사용하면 요소를 안전하게 제거 할 수 있습니다. myListIterator.remove();를 사용하여 제거 할 수도 있습니다.

+0

그래서 루프 대신 사용해야합니까? – DanielH

+0

작동해야합니다. –

+0

예, 작동합니다, 감사합니다! – DanielH

관련 문제