首页 > 解决方案 > How can I get a copy of a ArrayList() object instad of a refrence;

问题描述

if I ge

ArrayList<String> myList;
// add some stuff to myList
ArrayList<String> copyOf=myList;

copy will be a reference to myList, thus if I change copyOf, myList will change to. Hpw can I make coyyOf be a copy of myList, so if copyOf chnages, myList will not change.

标签: java

解决方案


使用将ArrayList集合作为参数的构造函数。

List<String> myCopy = new ArrayList<>(theArrayListToCopy);

根据 Javadoc,这“构造一个包含指定集合元素的列表,按集合迭代器返回的顺序排列。”


推荐阅读