二维 ArrayList 初始化行

2D ArrayList initializing rows

我正在为 Collapse 游戏制作一个 2D Arraylist 板,但现在只是做一个文本表示。我创建了板,但是当我尝试用 randomChar() 填充它时,所有行都获得相同的随机字符。 我做错了什么?

public static void createBoard(int rSize, int cSize) {
    ArrayList<Character> row = new ArrayList<Character>();
    ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>();

    for (int c = 0; c < cSize; c++) {
        board.add(row);

    }
    for (int r = 0; r < rSize; r++) {
        board.get(r).add(randomChar());
        //row.add(randomChar());
        // board.get(r).set(r, randomChar());
        }

    //prints out board in table form
    for (ArrayList<Character> r : board) {
        printRow(r);
    }
    System.out.println(board);

    } 

您将同一行多次添加到版块中。您必须添加唯一行:

for (int c = 0; c < cSize; c++) {
    board.add(new ArrayList<Character>());
}

因为在下一行中您存储了同一对象的引用:

for (int c = 0; c < cSize; c++) {
    board.add(row);
}

并且当您执行 board.get(r).add(randomChar()); 时,您将获得所有相同的值。 您应该为不同的板对象使用不同的数组:

for (int c = 0; c < cSize; c++) {
    board.add(new ArrayList<Character>());
}