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

  • 相关阅读:
    SRM 574 250 DIV2
    SRM 575 250 DIV2
    SRM 577 250 DIV2
    20181211-python1119作业郭恩赐
    20181207作业-郭恩赐
    python1119-20181206作业-郭恩赐提交
    python1119-20181205作业-郭恩赐提交
    python1119作业1-郭恩赐提交
    py1119_Linux学习_第二周总结
    小白都能看懂的block
  • 原文地址:https://www.cnblogs.com/afuu/p/12918018.html
Copyright © 2011-2022 走看看