克隆与在 Java 中复制数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18771899/
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
clone vs copying Array in Java?
提问by eagertoLearn
I have this bit of code, where I am making a copy of an array.
using System.arraycopy
seems more verbose than clone()
. but both give the same results. are there any advantages of one over the other?
here is the code:
我有这段代码,我正在制作一个数组的副本。usingSystem.arraycopy
似乎比clone()
. 但两者都给出相同的结果。一个比另一个有什么优势吗?这是代码:
import java.util.*;
public class CopyArrayandArrayList {
public static void main(String[] args){
//Array copying
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 0, copyTo, 0, 7);
char[] copyThree = new char[7];
copyThree=copyFrom.clone();
}
}
采纳答案by Jean Waghetti
The object you created with:
您创建的对象:
char[] copyThree = new char[7];
will be gc'd. The "final result" could be achieved with:
将被gc'd。可以通过以下方式实现“最终结果”:
char[] copyThree = copyFrom.clone();
Using System.arrayCopy
, copyFrom
and copyTo
need to meet certain requirements, like array types and size of the array.
使用System.arrayCopy
,copyFrom
并且copyTo
需要满足某些要求,例如数组类型和数组大小。
Using the clone
method, a new array will be created, with the same contents of the other array (same objects - the same reference, not different objects with same contents). Of course the array type should be the same.
使用该clone
方法,将创建一个新数组,其内容与另一个数组相同(相同的对象 - 相同的引用,而不是具有相同内容的不同对象)。当然数组类型应该是一样的。
Both ways copy references of the array contents. They not clone
the objects:
两种方式都复制数组内容的引用。他们不是clone
对象:
Object[] array = new Object[] {
new Object(),
new Object(),
new Object(),
new Object()};
Object[] otherArray = new Object[array.length];
Object[] clonedArray = array.clone();
System.arraycopy(array, 0, otherArray, 0, array.length);
for (int ii=0; ii<array.length; ii++) {
System.out.println(array[ii]+" : "+otherArray[ii]+" : "+clonedArray[ii]);
}
Provides:
提供:
java.lang.Object@1d256a73 : java.lang.Object@1d256a73 : java.lang.Object@1d256a73
java.lang.Object@36fb2f8 : java.lang.Object@36fb2f8 : java.lang.Object@36fb2f8
java.lang.Object@1a4eb98b : java.lang.Object@1a4eb98b : java.lang.Object@1a4eb98b
java.lang.Object@2677622b : java.lang.Object@2677622b : java.lang.Object@2677622b