我有一个不断更新的数组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];
}
但这似乎并不正确。请不要使用像深度复制等高级术语,因为我不知道那是什么意思。
当前回答
我在2D数组中遇到了类似的问题,并在这里结束。 我复制了主数组并更改了内部数组的值,当两个副本中的值都发生变化时,我感到惊讶。基本上这两个副本都是独立的,但包含对相同内部数组的引用,我必须对内部数组做一个数组的副本来得到我想要的。
这有时被称为深度复制。同样的术语“深度复制”也可能有完全不同的、可以说更复杂的含义,这可能会令人困惑,特别是对于那些不明白为什么他们复制的数组没有按照应有的方式运行的人来说。这可能不是OP的问题,但我希望它仍然能有所帮助。
其他回答
来自http://www.journaldev.com/753/how-to-copy-arrays-in-java的精彩解释
Java数组复制方法
Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array. System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination. Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.
我在2D数组中遇到了类似的问题,并在这里结束。 我复制了主数组并更改了内部数组的值,当两个副本中的值都发生变化时,我感到惊讶。基本上这两个副本都是独立的,但包含对相同内部数组的引用,我必须对内部数组做一个数组的副本来得到我想要的。
这有时被称为深度复制。同样的术语“深度复制”也可能有完全不同的、可以说更复杂的含义,这可能会令人困惑,特别是对于那些不明白为什么他们复制的数组没有按照应有的方式运行的人来说。这可能不是OP的问题,但我希望它仍然能有所帮助。
您可以尝试使用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);
对于数组的空安全副本,还可以使用可选的Object.clone()方法。
int[] arrayToCopy = {1, 2, 3};
int[] copiedArray = Optional.ofNullable(arrayToCopy).map(int[]::clone).orElse(null);