首页 > 编程语言 > 详细

java 之System.arraycopy() vs arrays.copyOf()

时间:2015-08-09 00:23:15      阅读:266      评论:0      收藏:0      [点我收藏+]

在java中,数组的复制可以有System.arraycopy与arrays.copyOf()两种选择,下面就详细介绍一下这两种方法的差别:

System.arraycopy

 int[] src = {1,2,3,4,5};
  
 int[] des = new int[10];

 System.arraycopy(arr, 0, copied, 1, 5); //5 is the length to copy
 
 System.out.println(Arrays.toString(des));  

输出结果:

[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

 

arrays.copyOf()

int[] des= Arrays.copyOf(src, 10); //10 the the length of the new array
System.out.println(Arrays.toString(des));
 
des= Arrays.copyOf(src, 3);
System.out.println(Arrays.toString(des));

结果:

[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]

 

本质区别:

 System.arraycopy()更灵活,但是需要提前new个数组出来

 arrays.copyOf(),参数少,不够灵活,只能指定复制的长度,无法设定偏移量

 

  

 

java 之System.arraycopy() vs arrays.copyOf()

原文:http://www.cnblogs.com/xkaisun/p/4714254.html

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