3

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.

Magnus
  • 589
  • 8
  • 26

2 Answers2

9

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();
}
dbank
  • 1,173
  • 1
  • 17
  • 29
Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • Correct. If you are wondering how a for each loop works in java check this link. (http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work) – Benjamin Winters Mar 22 '15 at 03:48
0

Also, You don't need to explicitly return the list from the test() method, since it's a field in myTest.

This would work perfectly fine,

public void test(){
            for(int i=0;i<5;i++){
                this.list[i] = new Case(); 
            }
        }
Nishit
  • 1,276
  • 2
  • 11
  • 25