System.arraycopy和Arrays.copyofrange的基本用法

最近接触的物联网项目,总是用到System.arraycopy和Arrays.copyofrange来进行数组之间的拷贝,因此,来记录下这两种数组拷贝的基本用法。
System.arraycopy
这个方法相当于把一个数组中的元素,拷贝到另一个数组里面,可以部分拷贝


/*
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
*/
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

我们首先来看下System.arraycopy方法的源码,可以看到,是native修饰,可以知道底层不是用java语言实现。
首先来看下第一个参数:src: the sorce array,即源数组,这个数组的元素是要拷贝到其他元素中的。
第二个参数:srcPos ,表面的意思为源数组的起始位置,即要拷贝到其他数组的的元素的起始索引位置。
第三个参数:dest,表面意思为目的地数组,即上面源数组中的元素,最终会拷贝到这个目的地数组里面。
第四个参数:destPos,目的地数组的起始位置,即要把源数组中的元素放到目的地数组中的起始位置
第五个参数:length,拷贝的数组元素长度。即拷贝源数组中的元素在新数组中的长度。

例如:要把bytes数组中的元素拷贝到data的字节数组中

   byte[] bytes = new byte[]{1, 2, 3, 4, 5};
        byte[] data = new byte[10];
        System.arraycopy(bytes, 0, data, 0, 5);
        for (byte b : data) {
            System.out.print(b);
        }

输出结果为:

1234500000

Arrays.copyOfRange
这个方法相当于截取数组中的某一部分元素,到一个新数组中

/*
	 * @param original the array from which a range is to be copied
     * @param from the initial index of the range to be copied, inclusive
     * @param to the final index of the range to be copied, exclusive.
*/
 public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

看到这里,不知道发现没有,这个方法最后还是调用System.arraycopy方法完成的截取。
首先来看参数:
第一个参数:original,即要截取的原始数组
第二个参数:from,即要从原始数组中的那个位置开始截取。。
第三个参数:to,要截取到的那个位置。

这里用的时候,遇到个坑,也怪自己没好好看代码,导致没截全。
在这里插入图片描述
其实注释里面写的很清楚,即进行数组截取的时候,包括第二个参数,不包括第三个参数

假如我们要将数组bytes中的第3位开始,截取到数组的末尾。

byte[] bytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
        byte[] copy = Arrays.copyOfRange(bytes, 3, bytes.length );
        for (byte b : copy) {
            System.out.print(b);
        }

输出结果:

45678

注意: 一般数组.length-1表示数组的最后末尾,但这里这个方法是不包括最后一位,使用的时候要注意。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值