System.arraycopy 和 Arrays.copyOf

System.arraycopy

 /*
native关键字 本地方法 System类 java.lang.System.class
参数说明:
src - 源数组。 
srcPos - 源数组中的起始位置。 
dest - 目标数组。 
destPos - 目标数据中的起始位置。 
length - 要复制的数组元素的数量。
*/
public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

Arrays.copyOf();该方法对于不同的数据类型都有相应的方法重载

/*
original - 要复制的数组 
newLength - 要返回的副本的长度 
newType - 要返回的副本的类型
*/
//基本数据类型
public static int[] copyOf(int[] original, int newLength) 
 //复杂数据类型   由U类型复制为T类型
public static <T,U> T[] copyOf(U[] original, int newLength, Class<?extends T[]> newType)

Arrays.copyOfRange()方法

/*
original 要复制的数组 
from初始索引 
to最终索引 
newType 要返回的副本类型
*/
//基本类型 可以使short、int、byte.....
public static <T> T[] copyOfRange(T[] original, int from, int to) 
{
    return copyOfRange(original, from, to, (Class<T[]>)original.getClass());
}
//复杂类型 由U类型转为T类型
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)

代码:

System.arraycopy

int a[]={0,1,2,3,4,5,6,7,8,9,11};
int ab[] = new int[5];
System.arraycopy(a, 0, ab, 0, 5);
for (int i : ab) {
    System.out.println(i);
}

Arrays.copyOf 基本数据类型

int a[]={0,1,2,3};
       //original a[]   newLength 新数组长度 如果大于老数组长度数组元素为0
        int c[] = Arrays.copyOf(a, 5);
        for (int i : c) {
            System.out.println(i);
        }

 Arrays.copyOf 复杂数据类型

// Short 数组
Short shortArr[] = new Short[]{5, 2, 15, 52, 10};
// copy  Short 数组 返回 Number[]数组
Number[] arr2 = Arrays.copyOf(shortArr, 5, Number[].class);
//遍历Number[] 
System.out.println("arr2 数组值:");
for (Number number : arr2) {
    System.out.println("Number = " + number);
}

 Arrays.copyOfRange

int a[]={0,1,2,3,4,5};
//original a[]数组 from初始索引 to最终索引
int ab[] = Arrays.copyOfRange(a, 0, 8);
for (int i : ab) {
    System.out.println(i);
}

复制数组: Arrays.copy 实现通过System.arraycopy完成

 

posted @ 2018-06-12 15:45  smokerBig  阅读(238)  评论(0编辑  收藏  举报