keid
keid

Reputation: 91

Only last added array in my list

I've got something like this:

List<int[]> myList= new ArrayList<int[]>(); 
int tmp[] = new int[size];

    for(int i = 0; i<anotherList.size(); i++) {                 
        for (int j = 0; j<size; j++) {              
            tmp[j] = anotherList.get(i)[j];                         
        }       
        myList.add(tmp);
    }

When I want to print myList, I see only last added tmp. Why?

    for(int i = 0 ; i<myList.size(); i++){                  
        for(int j=0; j<myList.get(i).length; j++){                              
            System.out.print(myList.get(i)[j]+ " ");
        } 
        System.out.println();           
    }   

Upvotes: 1

Views: 45

Answers (2)

copeg
copeg

Reputation: 8348

The tmp array is constructed outside the loops, and thus the same instance is being added to myList. To fix, add a different instance to the List at every iteration (eg create the array inside the first for loop)

Upvotes: 1

Warren Dew
Warren Dew

Reputation: 8928

Your code only ever creates one array named "tmp". You need to move the declaration of tmp inside the first for loop, instead of having it before the for loop.

Upvotes: 3

Related Questions