Error when adding or deleting a collection in the loop body: java.util.ConcurrentModificationException

First look at a piece of code:

 @Test
 public void test02(){
    
    
     List<String> list = new ArrayList<>(8);
     list.add("tom");
     list.add("jack");
     list.add("marry");
     list.add("wuwl");
     for(String string:list){
    
    
         if("wuwl".equals(string)){
    
    
             list.remove(string);
         }
     }
 }

The above code will definitely throw java.util.ConcurrentModificationExceptionan exception when it is running, and it will be list.remove(string);replaced with the list.add("gg")same exception.
Insert picture description hereEnter ArrayListline 909 of the source code:

final void checkForComodification() {
    
    
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

Use ArrayListof removethe method, modCountwill be a plus, but expectedModCountat the beginning of the cycle, the two are equal, by checkForComodificationthe determination method throws ConcurrentModificationExceptionan exception.
Insert picture description hereWhen the method ArrayListin the inner class Itris removeused to remove the element, the above two attributes will be re-assigned to be equal to ensure the normal operation of the collection.
Insert picture description hereChange the above demo to the following code to run normally:

@Test
public void test03(){
    
    

    List<String> list = new ArrayList<>(8);
    list.add("tom");
    list.add("jack");
    list.add("marry");
    list.add("wuwl");
    ListIterator<String> iterator = list.listIterator();
    while(iterator.hasNext()){
    
    
        if("wuwl".equals(iterator.next())){
    
    
            iterator.remove();
            iterator.add("gg");
        }
    }
    System.out.println(list);
}

ListIterator<String> iterator = list.listIterator();If it is replaced Iterator<String> iterator = list.iterator();, there is another removemethod, but no addmethod. The method of the two list Listis defined for the interface, in ArrayListthe, iterator()return directly Itr(), and listIterator()returns an inner class ListItrtype, the class inherits Itrand implements ListIteratorthe interface.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41885819/article/details/107191848