zoukankan      html  css  js  c++  java
  • java中的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);

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

    在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; }
  • 相关阅读:
    HDU 1251 统计难题
    HDU 1212 Big Number
    HDU 1205 吃糖果
    HDU 5776 Sum
    19 中山重现赛 1002 triangle
    7.29 线段树扫描线 ,矩形扫描
    一个很好的主席树总结
    7.14 单调栈 单调队列 +dp优化
    7.14 一个烦人的bug:dp[ q[tail] ] ---> dp[ tail ]
    7.13 cf573 补题
  • 原文地址:https://www.cnblogs.com/zh-ch/p/12726310.html
Copyright © 2011-2022 走看看