复制一个数组
问题描述:
我有一个不断更新的数组 a
.假设 a = [1,2,3,4,5]
.我需要制作 a
的完全副本并将其命名为 b
.如果 a
要更改为 [6,7,8,9,10]
,b
仍应为 [1,2,3,4,5]
.做这个的最好方式是什么?我尝试了一个 for
循环,例如:
I have an array a
which is constantly being updated. Let's say a = [1,2,3,4,5]
. I need to make an exact duplicate copy of a
and call it b
. If a
were to change to [6,7,8,9,10]
, b
should still be [1,2,3,4,5]
. What is the best way to do this? I tried a for
loop like:
for(int i=0; i<5; i++) {
b[i]=a[i];
}
但这似乎无法正常工作.请不要使用深拷贝等高级术语,因为我不知道那是什么意思.
but that doesn't seem to work correctly. Please don't use advanced terms like deep copy, etc., because I do not know what that means.
答
您可以尝试使用 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() 可能更好:
But, probably better to use clone() in most cases:
int[] src = ...
int[] dest = src.clone();