Java - 如何像填充2D数组一样填充多维(2D) ArrayList

4

在我熟悉面向对象编程之前,我曾创建过一个基本的井字棋游戏,并使用了一个数组来创建棋盘。

由于我没有正确理解如何使用对象,所以代码非常混乱,但我确实正确初始化了棋盘:

char[][] board = new char[3][3];
for (int i = 0; i < board.length; i++){
    for (int j = 0; j < board[i].length; j++){
        board[i][j] = '[]' //or something like that...don't remember exactly
    }
}

我的问题是如何使用ArrayList实现这个功能?
     ArrayList <ArrayList<Character>> board = new ArrayList(); // this initialization is not
    // wrong using Java 8 but for earlier versions you would need to state the type on both 
//sides of the equal sign not just the left
        for (int i = 0; i < board.size(); i++){
                for (int j = 0; j < board.get(i).size(); j++){
                    board.get(i).get(j).add('[]');
                }
            }

但是那并不起作用。

它不必完全像这样,我只是想了解如何处理多维ArrayList。

-谢谢

3个回答

8

与数组不同,您不能直接初始化整个ArrayList。但是,您可以事先指定预期的大小(当您使用非常大的列表时,这有助于提高性能,因此始终这样做是一个好习惯)。

int boardSize = 3;
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>(boardSize);
for (int i = 0; i < boardSize; i++) {
    board.add(new ArrayList<Character>(boardSize));
    for (int j = 0; j < boardSize; j++){
        board.get(i).add('0');
    }
}

2
我想点赞,但是我的声望不够...非常感谢! - Cornelius

2
主要区别在于你的原始代码中有一个多维基元数组(在这种情况下是char),你只需要为数组中的每个插槽分配一个新的基元值。
然而,现在你想要的是一个(ArrayList of ArrayList of Character)。当你创建ArrayList时,它是空的。为了进行操作,你需要填充它几个(ArrayList of Character),然后才能开始添加Character本身。
例如,
ArrayList <ArrayList<Character>> board = new ArrayList<>();

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

现在您可以开始将Character添加到您的列表中:
for (int i=0; i<3; i++) {
  for (int j=0; j<3; j++) {
    board.get(i).add('A');
  }
}

希望这有所帮助。

确实是这样...非常感谢您,先生。虽然我现在还不能点赞,但如果可以的话,我一定会的。 - Cornelius

1

首先,您必须在第一行正确初始化ArrayList,然后在每次运行第一个循环时都要初始化一个新的ArrayList:

ArrayList <ArrayList<Character>> board = new ArrayList<ArrayList<Character>>();
for (int i = 0; i < 3; i++){
    ArrayList<Character> innerList = new ArrayList<Character>();
    board.add(innerList);
    for (int j = 0; j < 3; j++){
        innerList.add('[');
    }
}

谢谢,这很有帮助。虽然我还不能点赞,但如果可以的话我会点赞的。然而,由于我正在使用Java 8,你最初说ArrayList初始化不正确的陈述是错误的。在Java 8中,你只需要在等号左边写类型,右边不需要写。 - Cornelius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接