Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my method return an array of nulls?

I'm using a foreach loop to iterate over an empty array, and populate it with objects. "Case" is a class with several methods and attributes.

My code looks like this:

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

The list which is returned from my method contains 5 nulls, when I expect it to contain 5 instantiated "Case" objects. I suspect this might be some sort of visibility problem, but I can't figure it out.

like image 560
Magnus Avatar asked Feb 20 '26 06:02

Magnus


1 Answers

The variable used in a for-each loop is just a reference to the current value of the array element. Assigning to that variable does not affect the values stored in the array. You need to use a for loop like this:

for (int i = 0; i < list.length; i++) {
    list[i] = new Case();
}
like image 163
Brett Kail Avatar answered Feb 23 '26 06:02

Brett Kail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!