我收到以下错误:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:810)
at java.util.HashMap$KeyIterator.next(HashMap.java:845)
at sudoku.Main.solve2(Main.java:143)
at sudoku.Main.next2(Main.java:168)
at sudoku.Main.solve2(Main.java:153)
at sudoku.Main.main(Main.java:284)
我不明白java.util.HashMap$KeyIterator.next
和java.util.HashMap$HashIterator.nextEntry
错误消息,因为我无法HashSet
明确地获取 keySet,我假设 Iterator 默认情况下正在通过 keySet。
我没有使用线程,只是递归调用。这里发生了什么?
static void solve2(int row, int col, int [][]grid, ArrayList<HashSet<Integer>> availableNumsInRows,
ArrayList<HashSet<Integer>> availableNumsInColumns){
if (row>=grid.length){
System.out.println("solution found");
printSolvedGrid(grid);
System.out.println("move count for this sudoku is " + moveCounter);
moveCounter=0; //reset counter
return;
}
if( grid[row][col] != 0 ){
next2( row, col, grid, availableNumsInRows, availableNumsInColumns ) ;
}
else {
// Find a valid number for the empty cell
Iterator <Integer> iterator = availableNumsInRows.get(row).iterator();
for( int num = iterator.next() ; iterator.hasNext(); num = iterator.next())
{
if( checkRow(row,num,grid) && checkCol(col,num,grid) && checkBox(row,col,num,grid) )
{
grid[row][col] = num ;
availableNumsInRows.get(row).remove(new Integer(num));
availableNumsInColumns.get(col).remove(new Integer(num));
moveCounter++;
//printSolvedGrid(grid);
next2( row, col, grid, availableNumsInRows, availableNumsInColumns );
}
}
grid[row][col] = 0 ;
}
}
//helper function for the first solution approach
public static void next2( int row, int col, int [][] grid , ArrayList<HashSet<Integer>> availableNumsInRows,
ArrayList<HashSet<Integer>> availableNumsInColumns )
{
if( col < 8 ) //pass to next col
solve2( row, col + 1, grid, availableNumsInRows, availableNumsInColumns) ;
else //pass to next row
solve2( row + 1, 0, grid, availableNumsInRows, availableNumsInColumns) ;
}
编辑:
我将代码更改为:
while (iterator.hasNext())
{
num=iterator.next();
if( checkRow(row,num,grid) && checkCol(col,num,grid) && checkBox(row,col,num,grid) )
{
grid[row][col] = num ;
iterator.remove();
moveCounter++;
next2( row, col, grid, availableNumsInRows, availableNumsInColumns );
}
}
我仍然得到ConcurrentModificationException
,这是为什么?
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:810)
at java.util.HashMap$KeyIterator.next(HashMap.java:845)
at sudoku.Main.solve2(Main.java:148)
at sudoku.Main.next2(Main.java:175)
at sudoku.Main.solve2(Main.java:137)
at sudoku.Main.next2(Main.java:175)
at sudoku.Main.solve2(Main.java:159)
at sudoku.Main.next2(Main.java:175)
at sudoku.Main.solve2(Main.java:137)
at sudoku.Main.next2(Main.java:175)
at sudoku.Main.solve2(Main.java:159)
at sudoku.Main.next2(Main.java:175)
at sudoku.Main.solve2(Main.java:159)
at sudoku.Main.main(Main.java:291)
Java Result: 1