I have this piece of code in my class and it throws the java.util.ConcurrentModificationException on the bolded lines (indicated with** **)
public void solve() {
**puzzleSolve(set.size(), sequence , set);**
}
//private helper method
protected void puzzleSolve(int k, String s, ArrayList<Character> u){
ListIterator<Character> iter = u.listIterator();
while(iter.hasNext())
{
Character c = iter.next();
if(k==1){ //base case
if(isAnswer(s+u.get(0)))
System.out.println(s+u.get(0)+" is the correct sequence."+ '\n');
return;
}
else{
**iter.remove();**
**puzzleSolve(k-1, s+c , u);**
iter.add(c);
removeLastChar(s);
}
}
} //end of puzzleSolve method
Each of your recursive calls has its own
iter. So you're modifying the list via multiple iterators at the same time which is not allowed. You'll have to redesign...As to redesign - you could use
for (int i = 0; i < u.size(); i++)and remove theith element from the array before making the recursive call, then insert it back with add(i, element).I am not saying mine is a good design, but it may work...