2016-07-24 71 views
0

我試圖將arraylists添加到arraylist的arraylist我相信(抱歉,我是一個初學者),但每當我無效的臨時,所以我可以抓住下一行要添加的數據,它也會更改主要的數組列表。有沒有什麼辦法只複製這些值而不會指向相同的引用?更改添加的數組更改我添加的arraylist

for (int n=0; n!=cellCount+1; n++) 
     { 
      temp.add(inputFile.nextDouble()); 
      System.out.println(temp); 
     } 

     mainList.add(temp); 


    //} 
temp.clear(); 
System.out.println(mainList); 

打印: [0.0,4.0,6.0,9.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0,15.0]作爲最終前臨時ArrayList中被清除

[[]]由於mainList

+2

以後你也應該包括在您的代碼段的所有初始定義正在使用的變量(如本例中的「temp」)。這就是說,[這個問題已經回答](http://stackoverflow.com/a/5785754)。 –

回答

1

我假設temp是你ArrayList

當你這樣做:

mainList.add(temp); 

你把該數組列表的引用到mainList。它是不是它的副本,它是對它的引用。你只是每次重複使用相同的ArrayList

相反,建立在每個循環中ArrayList(然後你不需要clear),例如:

while (/*...whatever, there's clearly some loop here..*/) { 
    temp = new ArrayList(); 
    for (int n=0; n!=cellCount+1; n++) 
    { 
     temp.add(inputFile.nextDouble()); 
     System.out.println(temp); 
    } 

    mainList.add(temp); 
} 
System.out.println(mainList);