不确定为什么会发生越界异常

Unsure why out of bounds exception is happening

获取越界异常但不明白为什么。每次从数组列表中删除一个项目直到它为空时,我的递归函数都会调用自身。一旦它为空,该行就应该被填充,然后我们将值添加回列表。我认为在最后一个元素上它会因为列表长度而抛出异常,它不想删除最后一个元素。有没有办法解决?是否有可能是其他错误?

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.*;

class Main {
public static void main(String[] args) {
    int[][]board=new int[9][9];
    Solver solve = new Solver();
    ArrayList<Integer> choices = new ArrayList<>();
    choices.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));
    Collections.shuffle(choices);

    for(int i = 0; i < 9; i++){
        for(int j=0; j < 9; j++) {
            solve.fill(board, choices, i, j);
        }
    }
    }
}

class Solver {

public void fill(int board[][], ArrayList<Integer> choices, int 
row, int col) {
    int num = choices.remove(0);
    if (isValid(board, row, col, num) == false) {
        fill(board, choices, row, col);
    } else
        board[row][col] = num;
    return;
}


public boolean isValid(int board[][], int row, int col, int num) {

    if (checkRow(board, row, col, num) == true) 
            /*checkCol(board, row, col, num) == true)*/
        /*checkSqr(board, row, col, num) == true*/
        return true;
    return false;
}

public boolean checkRow(int board[][], int row, int col, int num) {
    boolean valid = true;
    int i = 0;
    while (i < 9) {
        if (board[i][col] == num) {
            return valid = false;
        }
        i++;
    }
    return valid;
}

预期结果是根据数独规则随机填充棋盘 [][]。 相反,我们得到 线程 "main" java.lang.IndexOutOfBoundsException 中的异常: 索引 0 超出了长度 0 的范围 在 Solver.fill(Solver.java:31) 在 Main.main(Solver.java:22)

确保在调用 int num = choices.remove(0); 之前您仍然有一个元素,您可以使用 List.isEmpty() like

if (choices.isEmpty()) {
    return;
}
int num = choices.remove(0);