数组拷贝的常用方法

clone

String[] a1 = {"a1", "a2"};
String[] a2 = a1.clone();

a1[0] = "b1"; //更改a1数组中元素的值
System.out.println(Arrays.toString(a1));   //[b1, a2]
System.out.println(Arrays.toString(a2));   //[a1, a2]

克隆 相比 new 更有效率。根据已知的对象,做克隆。

System.arraycopy()

系统级别的native原生方法,效率高。

参数含义是:

(原数组, 原数组的开始位置, 目标数组, 目标数组的开始位置, 拷贝个数)

int[] a1 = {1, 2, 3, 4, 5};
int[] a2 = new int[10];

System.arraycopy(a1, 1, a2, 3, 3);
System.out.println(Arrays.toString(a1)); // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(a2)); // [0, 0, 0, 2, 3, 4, 0, 0, 0, 0]

Arrays.copyOf

参数含义,(原数组,拷贝的个数)。

int[] a1 = {1, 2, 3, 4, 5};
int[] a2 = Arrays.copyOf(a1, 3);

System.out.println(Arrays.toString(a1)) // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(a2)) // [1, 2, 3]

Arrays.copyOfRange

Arrays.copyOfRange底层其实也是用的 System.arraycopy,只不过封装了一个方法.

参数含义:(原数组,开始位置,拷贝的个数)。

int[] a1 = {1, 2, 3, 4, 5};
int[] a2 = Arrays.copyOfRange(a1, 0, 1);

System.out.println(Arrays.toString(a1)) // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(a2)) // [1]

小结

  • System.arraycopy() 最先考虑使用。

猜你喜欢

转载自www.cnblogs.com/wuyicode/p/11253635.html