我正在为折叠游戏制作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);
}
答案 0 :(得分:5)
您正在多次向电路板添加相同的行。您必须添加唯一的行:
for (int c = 0; c < cSize; c++) {
board.add(new ArrayList<Character>());
}
答案 1 :(得分:1)
因为在以下行中存储了相同对象的引用:
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>());
}