Java ArrayList 复制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6536094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java ArrayList copy
提问by user309281
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
?
我有一个ArrayList
l1
10 的大小。我分配l1
给新的列表引用类型l2
。会l1
和l2
指向同一个ArrayList
对象吗?或者是ArrayList
分配给的对象的副本l2
?
When using the l2
reference, if I update the list object, it reflects the changes in the l1
reference type also.
使用l2
引用时,如果我更新列表对象,它也会反映l1
引用类型的变化。
For example:
例如:
List<Integer> l1 = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
l1.add(i);
}
List l2 = l1;
l2.clear();
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?
除了创建 2 个列表对象并对从旧到新的集合进行复制之外,还有没有其他方法可以将列表对象的副本分配给新的引用变量?
采纳答案by Jon Skeet
Yes, assignment will just copy the valueof l1
(which is a reference) to l2
. They will both refer to the same object.
是的,分配将刚刚复制值的l1
(这是引用)l2
。它们都将引用同一个对象。
Creating a shallow copy is pretty easy though:
不过,创建浅拷贝非常简单:
List<Integer> newList = new ArrayList<>(oldList);
(Just as one example.)
(仅举一个例子。)
回答by Sergii Zagriichuk
回答by JB Nizet
Java doesn't pass objects, it passes references (pointers) to objects. So yes, l2 and l1 are two pointers to the same object.
Java 不传递对象,它传递对象的引用(指针)。所以是的,l2 和 l1 是指向同一个对象的两个指针。
You have to make an explicit copy if you need two different list with the same contents.
如果您需要两个具有相同内容的不同列表,则必须进行显式复制。
回答by Alfredo Osorio
Yes l1
and l2
will point to the same reference, same object.
是的l1
,l2
将指向相同的引用,相同的对象。
If you want to create a new ArrayList based on the other ArrayList you do this:
如果要基于另一个 ArrayList 创建新的 ArrayList,请执行以下操作:
List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");
The result will be l1
will still have 2 elements and l2
will have 3 elements.
结果将l1
仍然有 2 个元素,l2
并将有 3 个元素。
回答by Harshal Waghmare
Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:
将值从 src ArrayList 复制到 dest Arraylist 的另一种便捷方法如下:
ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);
This is actual copying of values and not just copying of reference.
这是值的实际复制,而不仅仅是引用的复制。
回答by vaibhav agrawal
There is a method addAll()which will serve the purpose of copying One ArrayList to another.
有一个方法addAll()将用于将一个 ArrayList 复制到另一个的目的。
For example you have two Array Lists: sourceListand targetList, use below code.
例如,您有两个数组列表:sourceList和targetList,请使用以下代码。
targetList.addAll(sourceList);
targetList.addAll(sourceList);
回答by Basil Bourque
List.copyOf
? unmodifiable list
List.copyOf
? 不可修改列表
You asked:
你问:
Is there no other way to assign a copy of a list
有没有其他方法可以分配列表的副本
Java 9 brought the List.of
methods for using literals to create an unmodifiable List
of unknown concrete class.
Java 9 带来了List.of
使用文字来创建不可修改List
的未知具体类的方法。
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
List< LocalDate > dates = List.of(
today.minusDays( 1 ) , // Yesterday
today , // Today
today.plusDays( 1 ) // Tomorrow
);
Along with that we also got List.copyOf
. This method too returns an unmodifiable List
of unknown concrete class.
与此同时,我们也得到了List.copyOf
. 此方法也返回一个不可修改List
的未知具体类。
List< String > colors = new ArrayList<>( 4 ) ; // Creates a modifiable `List`.
colors.add ( "AliceBlue" ) ;
colors.add ( "PapayaWhip" ) ;
colors.add ( "Chartreuse" ) ;
colors.add ( "DarkSlateGray" ) ;
List< String > masterColors = List.copyOf( colors ) ; // Creates an unmodifiable `List`.
By “unmodifiable” we mean the number of elements in the list, and the object referent held in each slot as an element, is fixed. You cannot add, drop, or replace elements. But the object referent held in each element may or may not be mutable.
“不可修改”是指列表中的元素数量以及作为元素保存在每个插槽中的对象所指对象是固定的。您不能添加、删除或替换元素。但是每个元素中保存的对象所指对象可能是也可能不是可变的。
colors.remove( 2 ) ; // SUCCEEDS.
masterColors.remove( 2 ) ; // FAIL - ERROR.
See this code run live at IdeOne.com.
dates.toString(): [2020-02-02, 2020-02-03, 2020-02-04]
colors.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]
masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]
日期.toString(): [2020-02-02, 2020-02-03, 2020-02-04]
color.toString(): [AliceBlue, PapayaWhip, DarkSlateGray]
masterColors.toString(): [AliceBlue, PapayaWhip, Chartreuse, DarkSlateGray]
You asked about object references. As others said, if you create one list and assign it to two reference variables (pointers), you still have only one list. Both point to the same list. If you use either pointer to modify the list, both pointers will later see the changes, as there is only one list in memory.
您询问了对象引用。正如其他人所说,如果您创建一个列表并将其分配给两个引用变量(指针),您仍然只有一个列表。两者都指向同一个列表。如果您使用任一指针修改列表,则两个指针稍后都会看到更改,因为内存中只有一个列表。
So you need to make a copy of the list. If you want that copy to be unmodifiable, use the List.copyOf
method as discussed in this Answer. In this approach, you end up with two separate lists, each with elements that hold a reference to the same content objects. For example, in our example above using String
objects to represent colors, the color objects are floating around in memory somewhere. The two lists hold pointers to the same color objects. Here is a diagram.
所以你需要复制一份清单。如果您希望该副本不可修改,请使用List.copyOf
本答案中讨论的方法。在这种方法中,您最终会得到两个单独的列表,每个列表的元素都包含对相同内容对象的引用。例如,在我们上面使用String
对象来表示颜色的示例中,颜色对象在内存中的某处浮动。这两个列表包含指向相同颜色对象的指针。这是一个图表。
The first list colors
is modifiable. This means that some elements could be removed as seen in code above, where we removed the original 3rd element Chartreuse
(index of 2 = ordinal 3). And elements can be added. And the elements can be changed to point to some other String
such as OliveDrab
or CornflowerBlue
.
第一个列表colors
是可修改的。这意味着可以删除一些元素,如上面的代码所示,我们删除了原始的第三个元素Chartreuse
(索引 2 = 序号 3)。并且可以添加元素。并且可以将元素更改为指向其他一些元素,String
例如OliveDrab
或CornflowerBlue
。
In contrast, the four elements of masterColors
are fixed. No removing, no adding, and no substituting another color. That List
implementation is unmodifiable.
相比之下, 的四个元素masterColors
是固定的。没有去除,没有添加,也没有替代另一种颜色。该List
实现是不可修改的。