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

  • 相关阅读:
    etcd客户端c#
    【Python 2 到 3 系列】 关于除法的余数
    彻底搞定C指针--“函数名与函数指针”
    关于 函数指针和函数名 例子的疑难解答
    stat.h头文件,轻松获取文件属性
    C++指针之间的赋值与转换规则总结
    (转)mblog解读(二)
    (转)mblog解读(一)
    (转)renren-fast解读(二)
    (转)renren-fast解读(一)
  • 原文地址:https://www.cnblogs.com/hericwan/p/12400961.html
Copyright © 2020-2023  润新知