首页 > 编程语言 > 详细

数组拷贝的常用方法

时间:2019-07-27 10:00:32      阅读:78      评论:0      收藏:0      [点我收藏+]

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() 最先考虑使用。

 

数组拷贝的常用方法

原文:https://www.cnblogs.com/wuyicode/p/11253635.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!