简体   繁体   中英

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM