Cor*_*ius 3 java arrays arraylist multidimensional-array
不久前,在我习惯面向对象编程之前,我创建了一个基本的 TicTacToe 游戏,并使用数组创建了棋盘。
代码一团糟,因为我没有正确理解如何使用对象,但我确实正确地初始化了电路板:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是你将如何使用 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('[]');
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
它不必完全像这样,我只是想了解如何处理多维 ArrayLists。
-谢谢
与数组不同,您不能直接初始化整个 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');
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4208 次 |
最近记录: |