2015-05-26 15 views
1

只有最後添加的陣列我有這樣的事情:在我的名單

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

當我想打印myList中,我只看到最後添加的TMP。爲什麼?

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

回答

3

您的代碼只創建一個名爲「tmp」的數組。您需要將tmp的聲明移到第一個for循環中,而不是在for循環之前。

1

tmp數組是在循環外部構造的,因此將相同的實例添加到myList。要修復,請在每次迭代中向列表添加不同的實例(例如,在第一個for循環內創建數組)