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
.