码迷,mamicode.com
首页 > 其他好文 > 详细

System.arraycopy和arrays.copyOf

时间:2018-05-07 19:42:28      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:arrays   tcl   观察   jdk   数据类型   array   div   长度   native   

public static native void arraycopy(Object src,  int  srcPos, 
                              Object dest, int destPos,  
                                    int length);

这个是system.arraycopy()

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 <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); }

original - 要复制的数组 
newLength - 要返回的副本的长度 
newType - 要返回的副本的类型

//基本数据类型(其他类似byte,short···)  
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;  
    } 

观察其源代码发现copyOf(),在其内部创建了一个新的数组,然后调用arrayCopy()向其复制内容,返回出去。 
总结: 
1.copyOf()的实现是用的是arrayCopy(); 
2.arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。 
3.copyOf()在内部新建一个数组,调用arrayCopy()将original内容复制到copy中去,并且长度为newLength。返回copy; 

转自:https://blog.csdn.net/shijinupc/article/details/7827507

 

System.arraycopy和arrays.copyOf

标签:arrays   tcl   观察   jdk   数据类型   array   div   长度   native   

原文地址:https://www.cnblogs.com/heyboom/p/9003935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!