ArrayList的添加和删除操作实现原理图解

作者: 迦叶_金色的人生_荣耀而又辉煌 | 来源:发表于2020-12-24 07:22 被阅读0次

    上一篇 <<<Java集合类图总览
    下一篇 >>>


    Arraylist数据结构:集合底层使用动态数组实现,随机查询效率非常快,插入和删除需要移动整个数组、效率低。

    ArrayList添加操作交互图

    ArrayList删除操作

    实现原理: 数组移动,末位置为null

    //下标范围检测,看是否数组越界
    if (index >= size) {
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
    }
    //启动线程安全问题
    modCount++;
    //获得要删除的数据
    E oldValue = (E) elementData[index];
    /**
     * 判断需要移动的数据
     * a、假设现有数据[1,2,3,4,5],现在需要把3数据移除,传入的index为2
     * b、则需要移动的位数:总位数5-传入的2-1=2
     * c、也就是3删除后,4和5两个数左移,numMoved=2
     *
     */
    int numMoved = size - index - 1;
    
    if (numMoved > 0) {
        /**
         * 数据移动参数:
         * ---源----
         * elementData:现有数据
         * index + 1:从哪个下标开始往前移
         * ---目标----
         * elementData:移动到的目标数组是什么
         * index:需要往前移到哪个下标开始
         * ---移动的个数----
         * numMoved:需要移动多少个
         */
        System.arraycopy(elementData, index + 1, elementData, index,
                numMoved);
    }
    //末位置为null,数组长度不变
    elementData[--size] = null;
    return oldValue;
    

    相关文章

      网友评论

        本文标题:ArrayList的添加和删除操作实现原理图解

        本文链接:https://www.haomeiwen.com/subject/ekzhnktx.html