假设数组a,b。要把数组a中的元素拷贝到b中,如果直接b = a的话。就会使b指向a的储存区域,对b的修改也会引发a中元素的修改(浅拷贝)。
public class ShallowCopy {
public static void main(String[] args) {
int[] a = {1, 2};
int[] b = a;
b[1] = 7;
System.out.println("a[1] = " + a[1]);
}
}
此时控制台输出a[1] = 7。
如果我们希望b拷贝a而不和a指向同一块堆内存空间(深拷贝),我们大致有三种方法可以选择:
1、for /while循环,一个一个复制,这个就不多说了;
2、使用System类中的静态方法arraycopy/Arrays类中的copyOf:
public class CopyArrayByarraycopy {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4};
int[] b = new int[4];
System.arraycopy(a, 0, b, 0, a.length);
b[3] = 7;
System.out.println("Array a:");
for (int i : a)
System.out.print(i + " ");
System.out.println();
System.out.println("Array b:");
for (int j : b)
System.out.print(j + " ");
}
}
//导入Arrays类
import java.util.Arrays;
public class CopyArrayByCopyof
{
public static void main(String[] args)
{
int[] a = new int[10];
//copyOf方法
int[] copy = Arrays.copyOf(a, a.length * 2);
//第一个参数为要拷贝的数组名,第二个为拷贝数组的大小(不限定大小,可用于扩大数组,如可以是a.length * 2)
System.out.println(a[1] + " " + copy[2] );
}
}
两者关系如下,可以看到copyOf调用arraycopy:
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
3、数组对象的clone方法:
public class CopyArrayByClone {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4};
int[] b = a.clone();
a[0] = 91;
b[1] = 7;
System.out.println("Array a:");
for (int i : a)
System.out.print(i + " ");
System.out.println();
System.out.println("Array b:");
for (int j : b)
System.out.print(j + " ");
}
}