【问题标题】:How to replace contents of arraylist with the contents of another arraylist?如何用另一个arraylist的内容替换arraylist的内容?
【发布时间】:2016-01-23 13:26:17
【问题描述】:

我想将一个数组列表的内容完全替换为另一个数组列表的内容。 例如,

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;

当我尝试这样做时,它会出现这种奇怪的行为,即数组列表的大小会随着更多元素而翻倍。我不想要一个两倍于原始数组列表大小的数组列表,我只想用新数组列表覆盖旧数组列表,其中新旧数组列表的内容相同。有没有办法在没有某种循环的情况下做到这一点,或者这是我唯一的选择?谢谢你和恳求

【问题讨论】:

  • 当我尝试它时,它确实取代了它。
  • newlist.add("OfLegends"): 应该是 ; :)
  • newlist.add("League")之后也是一个分号

标签: java oop arraylist


【解决方案1】:
old.clear(); 
old.addAll(newList);

这将清除旧列表并将引用的副本从 newList 添加到旧列表。如果您对旧列表进行更改,新列表将不受影响(反之亦然)。

请注意,就您的代码而言,您将旧列表设置为与新列表相同的对象引用。更改其中一个列表(使用add()remove())将更改另一个,因为它们共享相同的底层对象。

【讨论】:

  • 它使用System.arraycopy,这是一种原生方法
【解决方案2】:

我尝试了以下方法:

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]

看来您的代码正在运行。

【讨论】:

  • 这是不正确的,old 只是对newList 的引用,而不是真正的副本。尝试修改新的,旧的也会神奇地改变。
【解决方案3】:

这是您要查找的构造函数:

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

public ArrayList(Collection&lt;? extends E&gt; c)

按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2016-02-18
    • 2013-06-06
    • 2014-06-15
    • 1970-01-01
    相关资源
    最近更新 更多