0

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;
    }

}
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
Himanshu Sharma
  • 511
  • 5
  • 12

1 Answers1

0

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 e.g. 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.

Himanshu Sharma
  • 511
  • 5
  • 12