[英]Unexpected outputs from two different ways of adding an ArrayList to another
在以下某些程序中:
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp=new ArrayList<Integer>();
我想在結果中添加temp
result.add(new ArrayList<Integer>(temp));
那么最終的輸出是正確的,但是如果我使用
result.add(temp);
那么我的最終輸出是錯誤的。 為什么? 謝謝您的幫助!
這個result.add(new ArrayList<Integer>(temp))
和這個result.add(temp)
都將在result
產生相同的內容
如果沒有清楚地了解所需的輸出,我將看不到代碼的實際錯誤。
此外,更好的做法是將ArrayList稱為左側的List
並在右側使用<>
菱形。 使您的編碼更輕松,更清晰:
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
temp.add(1);
temp.add(2);
result.add(temp);
System.out.println("Result: " + result);
輸出與指定的完全相同,並且為List<List<Integer>>
:
結果:[[1,2]]
你打電話時:
result.add(new ArrayList<Integer>(temp));
temp
被復制到新的ArrayList中,最終結果將包含“未修改”的副本。
通過致電:
result.add(temp)
您將temp
本身添加到result
以便稍后在temp
將反映在result
(這是您描述的不需要的行為)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.