2014-07-20 41 views
1
List<List<Integer>> result = new ArrayList<List<Integer>>(); 
ArrayList<Integer> temp = new ArrayList<Integer>(); 
temp.add(5);temp.add(6); 
result.add(temp); 
temp.clear(); 

我編寫了類似上面的代碼,當我調試代碼時,我發現結果包含1的大小,但值(5,6,...)我在應用清除功能後會丟失,任何人都可以解釋爲什麼?Java ArrayList.clear()函數

+5

您沒有清除結果列表,所以它仍然有一個元素(一個空列表)。 – Keppil

+0

@StefanoSanfilippo它似乎只是想刪除2D列表中的一個項目? –

+0

對不起,我的意圖是清除溫度不是結果列表。我的意思是在清除臨時成員之後,即使結果的列表也受到影響 – i3wangyi

回答

1

這行代碼

result.add(temp); 

添加一個參考temp導致,下一行

temp.clear(); // <-- here 

清除溫度。我想你想的temp複印件(這樣你可以清楚再沒有temp改變result),因此,

result.add(new ArrayList<Integer>(temp)); // <-- copy temp. 

然後清除temp不會result改變數值。

+0

@Keppil謝謝,我已經編輯過了。更好? –

+0

我不知道深層和普通/ – i3wangyi

+0

有什麼區別@ElliottFrisch是的,這很好地解釋了我的困惑。我甚至不知道參考事情會發生在java – i3wangyi

5

您有列表。此代碼後

List<List<Integer>> result = new ArrayList<List<Integer>>(); 
ArrayList<Integer> temp = new ArrayList<Integer>(); 
temp.add(5);temp.add(6); 
result.add(temp); 

的情況是這樣的

     ┌───> 5 
result ─────> tmp ───┤ 
        └───> 6 
  • result列表包含一個元素,這是tmp列表
  • tmp列表包含兩個元素56

temp.clear(); 

形勢的變化,以

  // ↓↓↓ `temp.clear()` affects only this list 
result ─────> tmp 

所以現在

  • tmp列表爲空
  • result仍含有tmp列表這就是爲什麼它的大小爲1
+0

+1的情況的圖形表示:) – GameDroids

1

temp參考到一個ArrayList對象。

ArrayList<Integer> temp; 

這添加參考到結果列表。

result.add(temp); // adds a copy of the reference, not a copy of the list. 

這清除原來只有列表(除了result列表)

temp.clear(); 

注:Java只有referencesprimitives,沒有其他類型。

我怎麼能這樣做,以避免這種情況?複製臨時列表?

你希望每一個新的列表,創建一個新的。相反temp.clear的()調用

temp = new ArrayList<>(); 

理想情況下,你應該甚至不應該重用本地變量,除非它有異曲同工之妙。

// don't use temp again. 
List<Integer> temp2 = new ArrayList<>(); 

BTW我主張你再使用可變對象,以最大限度地提高性能。你應該只在你測量了這個分配率的問題後才這樣做,並且你知道你在做什麼。

+0

謝謝@peter我該怎麼做才能避免這種情況?複製臨時列表? – i3wangyi

+0

@ i3wangyi加入我的回答。 –