问题描述
我有一个大小为 10 的 ArrayList
l1
.我将 l1
分配给新的列表引用类型 l2
.l1
和 l2
会指向同一个 ArrayList
对象吗?或者是分配给 l2
的 ArrayList
对象的副本?
I have an ArrayList
l1
of size 10. I assign l1
to new list reference type l2
. Will l1
and l2
point to same ArrayList
object? Or is a copy of the ArrayList
object assigned to l2
?
当使用 l2
引用时,如果我更新列表对象,它也会反映 l1
引用类型的变化.
When using the l2
reference, if I update the list object, it reflects the changes in the 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 a list object to a new reference variable, apart from creating 2 list objects, and doing copy on collections from old to new?
推荐答案
是的,赋值只是将 l1
的 value(这是一个引用)复制到 l2
.它们都将引用同一个对象.
Yes, assignment will just copy the value of l1
(which is a reference) to l2
. They will both refer to the same object.
创建浅拷贝很容易:
List<Integer> newList = new ArrayList<>(oldList);
(举个例子.)
这篇关于Java ArrayList 拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!