Arrays.copyOf()与System.arraycopy()的源码分析
来源:互联网 发布:粘土淘宝 编辑:程序博客网 时间:2024/04/30 04:06
由于刚开始写博客,格式内容什么的比较乱,今天查资料找到一篇简单明了的,转载一下(http://chinesethink.iteye.com/blog/1568528):
首先观察先System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)的实现方式:
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。
该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。
再来看看Arrays.copyOf();该方法对于不同的数据类型都有相应的方法重载。
//非基本类型 public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { 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; } //基本数据类型 public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
original - 要复制的数组
newLength - 要返回的副本的长度
newType - 要返回的副本的类
观察其源代码发现copyOf(),在其内部创建了一个新的数组,然后调用arrayCopy()产生新的数组对象,返回出去。
总结:
1.copyOf()的实现是用的是arrayCopy();
2.arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。
3.copyOf()在内部新建一个数组,是用arrayCopy()将oldArray内容复制到newArray中去,并且长度为newLength。返回newArray;
0 0
- Arrays.copyOf()与System.arraycopy()的源码分析
- System.arraycopy 与 Arrays.copyOf 分析
- Java编程:Arrays.copyOf()与System.arraycopy()的分析
- System.arraycopy() 与 Arrays.copyOf()两个方法的区别
- System.arraycopy()和Arrays.copyOf()的区别
- System.arraycopy 和 Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- System.arraycopy()和Arrays.copyOf()的区别
- Arrays.copyOf(...)和System.arraycopy(...)
- Arrays.copyOf 和System.arraycopy
- Arrays.copyOf(...)和System.arraycopy(...)
- System.arraycopy和Arrays.copyOf
- Arrays.copyOf(...)和System.arraycopy(...)
- java数组的四种拷贝方法的性能分析:for、clone、System.arraycopy、Arrays.copyof
- System.arraycopy、Arrays.copyOf和ArrayList的toArray介绍
- Arrays.copyOf和System.arraycopy之间的区别
- Java数组的复制Arrays.copyOf()、System.arraycopy()、nums.clone()
- Java中System.arraycopy()和Arrays.copyOf()的区别
- hasMoreElements的用法
- 微信操作整理
- HNOI 2014 Day1 米特运输
- Coreseek:区段查询及增量索引代替实时索引
- 利用扩展事件和警报实时监控死锁-命令方式
- Arrays.copyOf()与System.arraycopy()的源码分析
- Java Observable 模式
- const char*, char const*, char*const的区别
- thunar 启动特别慢
- WiFi共享精灵出错之错误代码简介篇
- myeclipse 安装 ibatis 插件 自动生成java代码
- [leetcode]Remove Duplicates from Sorted Array
- qtp12录制模式
- 异常记录