Thursday, October 13, 2011

ConcurrentModificationException in the nutshell

package com.sopovs.moradanen;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConcurrentModificationExceptionTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList(Arrays.asList("first"));
        for (String el : list) {
Results in

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(
at java.util.ArrayList$
at com.sopovs.moradanen.ConcurrentModificationExceptionTest.main(

Update: This may look strange, though...

ArrayList<String> list = new ArrayList<String>(Arrays.asList("foo", "bar"));
for (String el : list) {
    //Capacity will not be increased, but iterator will fail...

No comments:

Post a Comment