zoukankan      html  css  js  c++  java
  • ArrayList是如何实现的,ArrayList和LinedList的区别?ArrayList如何实现扩容。

    ArrayList比较简单,主要是通过数组来实现的

    需要注意的是其初始容量是10

        /**
         * Default initial capacity.
         */
        private static final int DEFAULT_CAPACITY = 10;

    需要注意增长方法grow()

    /**
         * Increases the capacity to ensure that it can hold at least the
         * number of elements specified by the minimum capacity argument.
         *
         * @param minCapacity the desired minimum capacity
         */
        private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }

    只要size > 数组的长度,就会触发grow,其中增长比例是原来的容量的一半

            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);

    然后把原来数组的内容拷贝到新的数组

    ============================================分割线========================================================

    ArrayList和LinkedList的区别

    ArrayList是通过数组来实现的,读取性能很高,随机访问时间复杂度为O(1),适用于读大于写的场景,无序数据

    LinkedList是是通过双向队列来实现的,更新效率更高,写只需要修改前后两个节点的相关引用,但是读取效率比较低,需要最多遍历一半长度的队列,适用与写大于读的场景,有序数据

  • 相关阅读:
    Weebly轻松创建个人网站
    人生如游戏
    1 欧拉角与四元数计算机动画笔记
    图形学相关的一些数学基础书
    1047 Student List for Course (25 分)
    1124 Raffle for Weibo Followers (20 分)
    1065 A+B and C (64bit) (20 分)
    1036 Boys vs Girls (25 分)
    1039 Course List for Student (25 分)
    1054 The Dominant Color (20 分)
  • 原文地址:https://www.cnblogs.com/afuu/p/12918018.html
Copyright © 2011-2022 走看看