java的数组列表复制 [英] java arraylist copy

查看:104
本文介绍了java的数组列表复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大小10的的ArrayList L1我分配L1到新的列表的引用类型12。
将L1和L2指向同一个ArrayList对象?或ArrayList对象的拷贝被分配到12。
因为使用L2参考,如果我更新列表对象,它反映了L1引用类型也更改。

I have a ArrayList l1 of size 10. I assign l1 to new list reference type l2. Will l1 and l2 point to same arraylist object? Or a copy of arraylist object is assigned to l2. Because Using l2 reference, if I update the list object, it reflects the changes in l1 reference type also.

如。

List<Integer> l1 = new ArrayList<Integer>();
for(int i=1;i<=10;i++)
   l1.add(i);
List l2 = l1;
l2.clear();

有没有清单对象的拷贝分配给新的参考变量,除了创建2列表对象,并在集合做副本从旧到新没有其他的办法?

Is there no other way to assign a copy of list object to new reference variable, apart from creating 2 list objects, and doing copy on collections from old to new?

在此先感谢

推荐答案

是,分配将只复制的 L1 的(这是一个引用) 12 。他们都将引用相同的对象

Yes, assignment will just copy the value of l1 (which is a reference) to l2. They will both refer to the same object.

创建浅拷贝是pretty虽然容易:

Creating a shallow copy is pretty easy though:

List<Integer> newList = new ArrayList<Integer>(oldList);

(只是作为一个例子。)

(Just as one example.)

这篇关于java的数组列表复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆