This question already has answers here:
What is the default initialization of an array in Java?
                                
                                    (7个答案)
                                
                        
                                去年关闭。
            
                    
我只想填写未初始化数组的顶行和底行:

for (int i = 0; i < ROWS; i++) {
    for (int j = 0; j < COLUMNS; j++) {
        if (i == 0 || i == (ROWS - 1)) {
            values[i][j] = i;
        }
    }
}


但是,当我这样做时,它会用0填充之间的所有行:

0000000000
0000000000
0000000000
0000000000
4444444444


为什么会这样呢?

最佳答案

只需显式访问顶部和底部的行:

for (int i=0; i < ROWS; i+=ROWS-1) {
    for (int j=0; j < COLUMNS; j++) {
        values[i][j] = i;
    }
}


这避免了不必要地迭代每一行。请注意,您看到的零可能是int数组的默认值。

07-24 21:30