So I am getting the following runtime error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Solution.getAnswers(Solution.java:53)
at Solution.getAnswers(Solution.java:44)
at Solution.getAnswers(Solution.java:44)
at Solution.getEquations(Solution.java:28)
at Solution.main(Solution.java:22)
Now I have read up on the exception and am confused as to why this is happening, since to my knowledge I do not execute any code asynchronously. I know an array list is not thread safe, but I am not sure why adding values to a list would be a problem. Also I did not think I would have concurrency issues using recursion.
If any one could shed some light on the issue, and why it is happening it would be much appreciated! My code is below, and I believe the error originates in the recursive method found at the end of my code.
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
long result = getEquations(a,b);
System.out.println(result);
}
private static long getEquations(int a, int b) {
ArrayList<Integer> answers = new ArrayList<Integer>();
getAnswers(a,b,answers);
return answers.stream().mapToInt(x->x).distinct().count();
}
private static void getAnswers(int a, int b, ArrayList<Integer> answers){
if(a==0 && b==0) return;
if(a==1 && b == 0) {
answers.add(1);
return;
}
if(a==0 && b == 1) {
answers.add(2);
return;
}
if(a>0){
a-=1;
getAnswers(a,b,answers);
for(Integer value : answers){
answers.add(1+value);
answers.add(1*value);
}
return;
}
if(b>0){
b-=1;
getAnswers(a,b,answers);
for(Integer value : answers){
answers.add(2+value);
answers.add(2*value);
}
return;
}
}
}