2015-04-21 96 views
4

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

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); 

    } 

回答

5

您正在向电路板多次添加相同的行。因为在下面要存储同一对象的参考线

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

Aaaaah,好的。我想到了这一点,但并没有想到发生了这种情况。谢谢! –

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>()); 
}