zoukankan      html  css  js  c++  java
  • Java 数组拷贝方法 System.arraycopy


    System类提供的数组拷贝方法:

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


    数组拷贝方法,在读ArrayList源码的时候,频繁遇到,刚开始,囫囵吞枣的一带而过,知道个大概意思就算了,
    不过,读到下面这里的时候,就有点蒙圈了,这种时段,当然沉下心来,慢慢看看。
    public E remove(int index) {
            rangeCheck(index);
    
            modCount++;
            E oldValue = elementData(index);
    
            int numMoved = size - index - 1;
            if (numMoved > 0)
                System.arraycopy(elementData, index+1, elementData, index,
                                 numMoved);
            elementData[--size] = null; // clear to let GC do its work
    
            return oldValue;
        }

    从方法上来看,就是移除list中指定位置的元素,后面的元素依次向前移位1个位置

    从底层数组上来看,就是将数组指定位置之后的元素,依次往前移位1个位置(怎么是一样的)

    然后就到了正题:

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

    src : 原数组

    srcPos : 原数组指定位置(指定位置开始)

    dest : 目标数组

    destPos : 目标数组指定位置(指定位置开始)

    length : 移动的元素数量

    一句话就是,把src数组从srcPos位置开始,移动 length 个元素 覆盖到 dest数组的destPos 位置开始的length个元素

    当然,注意数组越界异常 :  java.lang.ArrayIndexOutOfBoundsException

     srcPos 、destPos 越界,算越界

    length 小于0 , 大于 src,dest 数组 的长度,算越界

    srcPos + length,destPos + length 也算越界

    打完,收工

  • 相关阅读:
    react脚手架搭建及配置
    mac使用技巧
    nginx配置
    vue常见前端UI库
    自定义指令
    代码缩进修改
    webpack学习入门
    webpack使用extract-text-webpack-plugin打包时提示错误
    webpack未成功全局安装
    基于jQuery的AJAX实现三级联动菜单
  • 原文地址:https://www.cnblogs.com/Springmoon-venn/p/8309765.html
Copyright © 2011-2022 走看看