簡體   English   中英

如何用另一個arraylist的內容替換arraylist的內容?

[英]How to replace contents of arraylist with the contents of another arraylist?

我想完全用另一個arylylist的內容替換一個arraylist的內容。 例如,

ArrayList<String> old = new ArrayList<String>();
ArrayList<String> newlist = new ArrayList<String>();
old.add("Hi");
old.add("World");
newlist.add("League")
newlist.add("OfLegends"):
old = newlist;

當我嘗試這個時,它會做出這種奇怪的行為,其中arraylist的大小加倍了更多的元素。 我不想要一個兩倍於原始arraylist大小的arraylist,我只想用新的arraylist覆蓋舊的arraylist,其中新舊arraylist的內容是相同的。 有沒有辦法在沒有某種循環的情況下做到這一點,或者這是我唯一的選擇? 謝謝你,請求

old.clear(); 
old.addAll(newList);

這將清除舊列表,並將newList中的引用副本添加到舊列表中。 如果您對舊列表進行更改,新列表將不受影響(反之亦然)。

請注意,您的代碼代表,您將舊列表設置為與新列表相同的對象引用。 更改其中一個列表(使用add()remove() )將更改另一個列表,因為它們共享相同的基礎對象。

我嘗試了以下方法:

ArrayList<String> old = new ArrayList<String>();
ArrayList<String> newList = new ArrayList<String>();
old.add("Hi");
old.add("World");
newList.add("League");
newList.add("OfLegends");
System.out.println(old.toString());
old = newList;
System.out.println(old.toString());
System.out.println(newList.toString());

我的輸出是:

[Hi, World]
[League, OfLegends]
[League, OfLegends]

所以看起來你的代碼工作正常。

這是您正在尋找的構造函數:

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)

public ArrayList(Collection<? extends E> c)

按照集合的迭代器返回的順序構造一個包含指定集合元素的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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