为什么不能使用foreach周期将1D数组分配给2D数组?

Lep*_*aun 0 java arrays foreach

我有一个返回一维数组的方法。我想循环调用该方法并将结果存储在2D数组中。当使用foreach循环不起作用时,数组结果充满了空指针。

//this doesn't work
...
double[][] results = new double[20][];
for(double[] result : results){
        result = method();
}
...
public double[] method(){
        double[] ret = new double[15];
        //populate ret and do other stuff...
        return ret;
}
Run Code Online (Sandbox Code Playgroud)

但是,当使用常规的“ for”循环遍历数组时,它神奇地起作用了!

...
double[][] results =  new double[20][];
for(int i=0;i<20;i++){
        results[i]=method();
}
...   
public double[] method(){
        double[] ret = new double[15];
        //populate ret and do other stuff...
        return ret;
}
Run Code Online (Sandbox Code Playgroud)

为什么?

Lui*_*oza 5

因为在增强for循环中,您访问分配给变量的数组的每个对象引用的副本,并且您正在修改此变量的值,而不是其内容。

for (double[] result :  results) {
     //here result is just a copy of results[0], results[1] and on...
     //if you modify value of result i.e. assigning a new value
     //you're just changing the value of the current variable
     //note that if you modify an object inside the variable is reflected
     //since you're updating the state of the reference, which is valid
}
Run Code Online (Sandbox Code Playgroud)

该代码可以翻译为:

for (int i = 0; i < results.length; i++) {
     double[] result = results[i];
     //this explains why the enhanced for doesn't work
     result = method();
}
Run Code Online (Sandbox Code Playgroud)