简体   繁体   中英

Concurrent Modification Exception while adding elements to ArrayList recursively

Getting Concurrent Modification Exception while adding elements to ArrayList recursively.

import java.util.*;

public class Hello {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        
        System.out.println(gss(str));
    }

    public static ArrayList<String> gss(String str) {
        if(str.length() == 0){
            ArrayList<String> list = new ArrayList<String>();
            list.add("");
            return list;
        }
        
        ArrayList<String> list = gss(str.substring(1));
        for(String temp : list){
            list.add(str.charAt(0)+temp);  // Problem  
        }
        
        return list;
    }

}

Solution: To just form new ArrayList at each call stack and return it.

import java.io.*;

import java.util.*;

public class Main {

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);
    String str = sc.next();
    
    System.out.println(gss(str));
}

public static ArrayList<String> gss(String str) {
    if(str.length() == 0){
        ArrayList<String> list = new ArrayList<String>();
        list.add("");
        return list;
    }
    
    ArrayList<String> list = gss(str.substring(1));
    ArrayList<String> listToReturn = new ArrayList<>();
    
    for(String temp : list){
        listToReturn.add(temp);
    }
    for(String temp : list){
        listToReturn.add(str.charAt(0) + temp);    
    }
    
    return listToReturn;
}

}

I have recently come across this blog .

Which says, It uses a transient variable called modCount , which keeps track of how many times a list is modified structurally. Structural modifications are those that change the size of the list, which may affect the progress of iteration and may yield incorrect results. Both Iterator and ListIterator uses this field to detect unexpected change. Other methods of List which structurally modify List also uses this method eg add(), remove() .

Cause: The real cause of ConcurrentModficationException is inconsistent modCount . When you are iterating over ArrayList then Iterator's next() method keep track of modCount . If you modify the collection by adding or removing element then modCount will change and it will not match with the expected modCount , hence Iterator will throw ConcurrentModificationException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM