为什么我的方法 return 是一个空数组?

Why does my method return an array of nulls?

我正在使用 foreach 循环迭代一个空数组,并用对象填充它。 "Case" 是具有多个方法和属性的 class。

我的代码如下所示:

public class Test {

private Case [] list = new Case[5];

public Case [] test(){
    for(Case myCase : list){
        myCase = new Case(); 
    }

    return list; //This list contains 5 nulls, but should contain five "Case" objects.
}

public static void main(String[] args){
    Test myTest = new Test();
    myTest.test();
}}

从我的方法返回的列表包含 5 个空值,而我希望它包含 5 个实例化的 "Case" 对象。我怀疑这可能是某种可见性问题,但我无法弄清楚。

for-each 循环中使用的变量只是对数组元素当前值的引用。分配给该变量不会影响存储在数组中的值。您需要像这样使用 for 循环:

for (int i = 0; i < list.length; i++) {
    list[i] = new Case();
}

此外, 您不需要明确 return test() 方法中的列表,因为它是 myTest 中的一个字段。

这会很好用,

public void test(){
            for(int i=0;i<5;i++){
                this.list[i] = new Case(); 
            }
        }