首页 > 技术文章 > java中的System.arraycopy

zh-ch 2020-04-18 15:55 原文

  /**
     * @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);

是一个本地方法,可以用来快速的复制数组

在ArrayList的删除中使用了该方法:

   /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);
      // 判断是否是删除最后一个元素  假如是最后一个元素则不需要进行数组复制
        int numMoved = size - index - 1;
        if (numMoved > 0)    
          // 假如不是删除最后一个,则将要删除的元素开始,把之后的元素通过copy的方法往前移一位,将需要删除的元素覆盖掉,然后再将最后一个元素置为null等待gc,达到删除目的
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
      elementData[
--size] = null; // clear to let GC do its work return oldValue; }

 

推荐阅读