我有一个不断更新的数组a。我们设a =[1,2,3,4,5]。我需要做一个完全相同的副本a,并称之为b。如果a改变为[6,7,8,9,10],b应该仍然是[1,2,3,4,5]。最好的方法是什么?我尝试了一个for循环:
for(int i=0; i<5; i++) {
b[i]=a[i];
}
但这似乎并不正确。请不要使用像深度复制等高级术语,因为我不知道那是什么意思。
我有一个不断更新的数组a。我们设a =[1,2,3,4,5]。我需要做一个完全相同的副本a,并称之为b。如果a改变为[6,7,8,9,10],b应该仍然是[1,2,3,4,5]。最好的方法是什么?我尝试了一个for循环:
for(int i=0; i<5; i++) {
b[i]=a[i];
}
但这似乎并不正确。请不要使用像深度复制等高级术语,因为我不知道那是什么意思。
当前回答
所有的解决方案,调用长度从数组,添加你的代码冗余空检查器考虑的例子:
int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
//What if array a comes as local parameter? You need to use null check:
public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}
我建议您不要白费力气,而是使用已经执行了所有必要检查的实用程序类。考虑一下apache commons中的ArrayUtils。你的代码变得更短:
public void someMethod(int[] a) {
int[] b = ArrayUtils.clone(a);
}
你可以在那里找到Apache commons
其他回答
如果你想复制下列文件:
int[] a = {1,2,3,4,5};
这是一条正确的道路:
int[] b = Arrays.copyOf(a, a.length);
数组。在小型数组上,copyOf可能比a.r onclone()更快。两者复制元素的速度相同,但clone()返回Object,因此编译器必须插入隐式转换为int[]。你可以在字节码中看到它,就像这样:
ALOAD 1
INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
CHECKCAST [I
ASTORE 2
您可以尝试使用System.arraycopy()
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
但是,在大多数情况下使用clone()可能更好:
int[] src = ...
int[] dest = src.clone();
您可以尝试在Java中使用Arrays.copyOf()
int[] a = new int[5]{1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
你可以使用
int[] a = new int[]{1,2,3,4,5};
int[] b = a.clone();
也
所有的解决方案,调用长度从数组,添加你的代码冗余空检查器考虑的例子:
int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
//What if array a comes as local parameter? You need to use null check:
public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}
我建议您不要白费力气,而是使用已经执行了所有必要检查的实用程序类。考虑一下apache commons中的ArrayUtils。你的代码变得更短:
public void someMethod(int[] a) {
int[] b = ArrayUtils.clone(a);
}
你可以在那里找到Apache commons