ArrayList插入指定位置源码分析

  1. System.arraycopy() 方法

    // 我们发现 arraycopy 是一个 native 方法,接下来我们解释一下各个
    //参数的具体意义
    /**
    *   复制数组
    * @param src 源数组
    * @param srcPos 源数组中的起始位置
    * @param dest 目标数组
    * @param destPos 目标数组中的起始位置
    * @param length 要复制的数组元素的数量
    */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
  • 在列表中插入新元素
    /**
     * 在此列表中的指定位置插入指定的元素。
     *先调用 rangeCheckForAdd 对index进行界限检查;然后调用 ensureCapacityInternal 方法保证capacity足够大;
     *再将从index开始之后的所有成员后移一个位置;将element插入index位置;最后size加1。
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //arraycopy()方法实现数组自己复制自己
        //elementData:源数组;index:源数组中的起始位置;elementData:目标数组;index + 1:目标数组中的起始位置; size - index:要复制的数组元素的数量;
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = element;
        size++;
    }
  1. 用实例来理解ArrayList指定位置插入
//ArrayList插入元素源码分析
        int[] a = new int[10];
        a[0] = 0;a[1] = 1;a[2] = 2;a[3] = 3;
        System.arraycopy(a,2,a,3,2);
        a[2] = 8;
        for(int i = 0; i < a.length; i++){
            System.out.print(a[i]+" ");
        }
        ArrayList<Integer> b = new ArrayList<>();
        b.add(0);b.add(1);b.add(2);b.add(3);
        b.add(2,8);
        for(int i : b){
            System.out.print(i+" ");
        }

 

posted @ 2022-04-12 17:45  panther125  阅读(194)  评论(0)    收藏  举报