블로그 이미지
암초보

calendar

1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

Notice

Tag

02-04 03:02
2013. 5. 15. 12:32 프로그래밍/Java

list같은 걸 돌리는 for문에서

remove를 호출할 때 발생...

java.util.ConcurrentModificationException


이유는 index 문제.. 생각해보면 금방 알 수 있듯이..

증가된 index와 list의 size를 비교하는데 있어서 문제가 발생하게된다.



아래와 같은 방법으로 해결하면 됩니다.


1. Take a copy of the collection , iterate over the copy and remove elements from the original. 

2. During iteration, build up a set of elements to remove, and then perform a bulk removal after iteration has completed.

3. Use an List implementation which can deal with concurrent modifications, like the CopyOnWriteArrayList



대충 이런식이 좋은거 같다.

List<String> list = new ArrayList<String>();
...
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String value = iterator.next();
    if (value.length() > 5) {
        iterator.remove();
    }
}


아래와 같이 for문도 두번.. 위의 for문안에 집어넣는다해도..
clone 하는 방식은 좋지 않은거 같다... 쓸데없이 만들필요가 있나..

List<String> toRemove = new ArrayList<String>();
for (String fruit : list) {
    if ("banane".equals(fruit))
        toRemove.add(fruit);
    System.out.println(fruit);
}
for (String fruit : toRemove) {
    list.remove(fruit);
}

'프로그래밍 > Java' 카테고리의 다른 글

Callable 과 Thread  (0) 2013.10.31
Comparator & Comparable 이용한 정렬  (0) 2013.05.20
업캐스팅  (0) 2011.09.27
추상화  (0) 2011.09.26
enum 활용  (0) 2011.09.25
posted by 암초보
2012. 10. 10. 13:23 O/S/Windows Server 2008 R2
posted by 암초보
2012. 2. 9. 10:39 프로그래밍/기타
자주사용하는 정규표현식 검색 : http://regexlib.com/Default.aspx
파폭 도구 :   http://sebastianzartner.de/firefoxExtensions/RExT/

'프로그래밍 > 기타' 카테고리의 다른 글

json parser oline  (0) 2013.10.22
로딩 이미지 생성 페이지  (0) 2013.06.26
Joda Time 라이브러리  (0) 2011.10.17
tomcat JVM 옵션 설정  (0) 2011.06.23
sftp 간단 접속 방법  (0) 2011.06.01
posted by 암초보