前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【编程基础】System.arraycopy()和 Arrays.copyOf()

【编程基础】System.arraycopy()和 Arrays.copyOf()

作者头像
程序员互动联盟
发布2018-03-12 17:10:33
1.1K0
发布2018-03-12 17:10:33
举报

在Java中如果要copy一个数组有两种系统api可以使用System.arraycopy()和Arrays.copyOf()。那么这两个方法有什么不同吗?下面一个例子来给大家展示一下:

1、System.arraycopy()

代码语言:javascript
复制
int[] arr = {1,2,3,4,5};
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
System.out.println(Arrays.toString(copied));

Output:

代码语言:javascript
复制
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

2、Arrays.copyOf()

int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new arraySystem.out.println(Arrays.toString(copied)); copied = Arrays.copyOf(arr, 3);System.out.println(Arrays.toString(copied));

Output:

代码语言:javascript
复制
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]

两种方法的不同之处在于Arrays.copyOf是通过创建一个新的数组来实现的copy,源码如下:

代码语言:javascript
复制
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied)); 
copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));

System.arraycopy()是往一个已经存在的数组copy,函数源码如下:

public static native void arraycopy(Object src, int srcPos,

Object dest, int destPos,

int length);

src - 源数组。 srcPos - 源数组中的起始位置。 dest - 目标数组。 destPos - 目标数据中的起始位置。 length - 要复制的数组元素的数量。 该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。

总结: 1.copyOf()的实现是用的是arrayCopy()。 2.arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。 3.copyOf()在内部新建一个数组,是用arrayCopy()将oldArray内容复制到newArray中去,并且长度为newLength,返回newArray。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2015-06-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员互动联盟 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档