System.arraycopy()和Arrays.copyOf()的区别
来源:互联网 发布:java se技术文档 编辑:程序博客网 时间:2024/04/28 19:23
先看看System.arraycopy()的声明:
public static native void arraycopy(Object src,int srcPos, Object dest, int destPos,int length);
src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。
该方法用了native关键字,说明调用的是其他语言写的底层函数。
再看Arrays.copyOf()
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
该方法对应不同的数据类型都有各自的重载方法
original - 要复制的数组
newLength - 要返回的副本的长度
newType - 要返回的副本的类型
仔细观察发现,copyOf()内部调用了System.arraycopy()方法
区别在于:
- arraycopy()需要目标数组,将原数组拷贝到你自己定义的数组里,而且可以选择拷贝的起点和长度以及放入新数组中的位置
- copyOf()是系统自动在内部新建一个数组,调用arraycopy()将original内容复制到copy中去,并且长度为newLength。返回copy; 即将原数组拷贝到一个长度为newLength的新数组中,并返回该数组。
总结
Array.copyOf()可以看作是受限的System.arraycopy(),它主要是用来将原数组全部拷贝到一个新长度的数组,适用于数组扩容。
0 0
- System.arraycopy()和Arrays.copyOf()的区别
- System.arraycopy 和 Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- Arrays.copyof 和 System.arraycopy区别
- Arrays.copyOf和System.arraycopy之间的区别
- Java中System.arraycopy()和Arrays.copyOf()的区别
- Arrays.copyOf(...)和System.arraycopy(...)
- Arrays.copyOf 和System.arraycopy
- Arrays.copyOf(...)和System.arraycopy(...)
- System.arraycopy和Arrays.copyOf
- Arrays.copyOf(...)和System.arraycopy(...)
- System.arraycopy() 与 Arrays.copyOf()两个方法的区别
- System.arraycopy、Arrays.copyOf和ArrayList的toArray介绍
- 在Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别
- 在Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别?
- Arrays.copyof()和System.arraycopy()方法总结
- Java方法之--System.arraycopy方法和Arrays.copyOf()
- 用 PGO 对C++程序执行性能进行优化
- Java包装类、装箱拆箱
- 设计模式-外观模式
- 网络库Asio交叉编译
- 代码中添加drawableLeft/drawableRight等
- System.arraycopy()和Arrays.copyOf()的区别
- POJ 3463 Sightseeing
- EditText设置不可编辑,可以复制功能(最简单)
- scala 实现WordCount
- select多选框的反显
- IO流——缓冲流之BufferedReader
- CCF 模板生成系统
- Android工具类---前后台判定、App卸载、安装、分享工具类
- React.js实现原生js拖拽效果及思考