Java之数组拷贝System.arraycopy()

Java提供了一个非常方便的字符串拷贝接口:System.arraycopy(), 很多容器(比如ArrayList, SimpleArrayMap)的的底层实现都能看到它的身影
1.原理:
其接口形式为:

public static native void arraycopy(Object var0, int var1, Object var2, int var3, int var4);

其中var0: 源数组
        var1:拷贝数据时,源数组的起始下标.
        var2:目的数组
        var3:拷贝数据时,目的数组的起始下标.
        var4:拷贝数据的长度.
其具体代码实现暂未找到,个人实现如下:

/**
 * This is used to copy a string from a source array to destination array.
 * @param source The source arrays.
 * @param sourcePoint The start index of the source arrays.
 * @param destination The destination arrays
 * @param destinationPoint The start index of the destination arrays.
 * @param length
 */
private static void arrayCopyDIY(int[] source, int sourcePoint,
                          int[] destination, int destinationPoint, int length){
    if (source == null || destination == null || length ==0) {
        return;
    }
    if (source.length <1 || destination.length <1){
        return;
    }
    if (source.length < length || destination.length < length){
        return;
    }
    for (int i = 0; i<length; i++){
        destination[destinationPoint+i] = source[sourcePoint+i];
    }
}
2.使用方法
Demo如下所示:
public static void main(String[] args){
    int[] sourceArray = new int[]{1,2,3,4,5,6};
    int[] DestinationArray = new int[4];
    System.out.println("Initial destinationArray="+ Arrays.toString(DestinationArray));
    System.arraycopy(sourceArray, 2, DestinationArray, 0, 4);
    System.out.println("Final destinationArray="+ Arrays.toString(DestinationArray));
}
输出:
Initial destinationArray=[0, 0, 0, 0]
Final destinationArray=[3, 4, 5, 6]

Process finished with exit code 0
3. 总结
1. Sysytem.arraycopy() 是一个用于数组间拷贝的工具.
2. 数组的打印可以用Array.toString(). 它可以将各种基本类型的数组转换为字符串.方便打印.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值