更优雅的方式来初始化数组元素的范围

时间:2014-02-04 22:08:34

标签: java

自从我做了任何java以来​​已经有几年了。我认为有一个更好的方式来写这个,不知道如何谷歌这个问题。

boardSpots[0][1] = new Pawn();
boardSpots[1][1] = new Pawn();
boardSpots[2][1] = new Pawn();
boardSpots[3][1] = new Pawn();
boardSpots[4][1] = new Pawn();
boardSpots[5][1] = new Pawn();
boardSpots[6][1] = new Pawn();
boardSpots[7][1] = new Pawn();

2 个答案:

答案 0 :(得分:2)

for (int i = 0; i < 8; i++) {
    boardSpots[i][1] = new Pawn();
}

答案 1 :(得分:1)

使用嵌套的for循环:

for (int i = 0; i < boardSpots.length; i++) {
    for (int j = 0; j < boardSpots[i].length; j++) {
        boardSpots[i][j] = new Pawn();
    }
}

Check this great source out on loops in Java.