Concurrent Modification exception

前端 未结 9 1477
谎友^
谎友^ 2020-11-22 14:36

I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent mo

9条回答
  •  一个人的身影
    2020-11-22 14:52

    I cannot understand why I keep getting it, even though I do not see any concurrent modifications being carried out.

    Between creating the iterator and starting to use the iterator, you added arguments to the list that is to be iterated. This is a concurrent modification.

        ListIterator it = s.listIterator();  
    
        for (String a : args)
            s.add(a);                    // concurrent modification here
    
        if (it.hasNext())
            String item = it.next();     // exception thrown here
    

    Create the iterator AFTER you've finished adding elements to the list:

        for (String a : args)
            s.add(a); 
    
        ListIterator it = s.listIterator();  
        if (it.hasNext())
            String item = it.next();
    

提交回复
热议问题