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

  • 相关阅读:
    vue基础知识
    git的创建使用
    使用express搭建服务器框架
    日常训练
    今日收获
    今日收获
    今日收获
    今日收获
    今日收获
    今日收获
  • 原文地址:https://www.cnblogs.com/afuu/p/12918018.html
Copyright © 2020-2023  润新知