簡體   English   中英

兩種將ArrayList添加到另一種方式的意外輸出

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM