• ArrayList


    ArrayList维护的数据结构是c++数组。创建方式是Arrays.copyOf

        public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
            @SuppressWarnings("unchecked")
            T[] copy = ((Object)newType == (Object)Object[].class)
                ? (T[]) new Object[newLength]
                : (T[]) Array.newInstance(newType.getComponentType(), newLength);
            System.arraycopy(original, 0, copy, 0,
                             Math.min(original.length, newLength));
            return copy;
        }
    

      

    ArrayList扩容会重新分配空间,建议在使用前估计好需要的容量大小。你可以通过构造函数传参,或者使用ensureCapacity

        /**
         * Increases the capacity of this <tt>ArrayList</tt> instance, if
         * necessary, to ensure that it can hold at least the number of elements
         * specified by the minimum capacity argument.
         *
         * @param   minCapacity   the desired minimum capacity
         */
        public void ensureCapacity(int minCapacity) {
            int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                // any size if not default element table
                ? 0
                // larger than default for default empty table. It's already
                // supposed to be at default size.
                : DEFAULT_CAPACITY;
    
            if (minCapacity > minExpand) {
                ensureExplicitCapacity(minCapacity);
            }
        }
    

      

    ArrayList扩容的默认方式是,增加1/2大小。           int newCapacity = oldCapacity + (oldCapacity >> 1);

        /**
         * 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);
        }
    

      

    ArrayList随机访问效率高,因为他使用的是数组。

  • 相关阅读:
    Online ddl 工具之pt-online-schema-change
    【MySql】mysql 慢日志查询工具之mysqldumpslow
    赶集网mysql开发36条军规
    MySQL数据库高并发优化配置
    mysql的表分区
    mysql 如果处理货币金钱类型
    bootstrab table+表格 select可编辑完整实例
    mongoDb 给表添加+ 删除字段
    mongoDb +Java+springboot
    java+数据库+D3.js 实时查询人物关系图
  • 原文地址:https://www.cnblogs.com/afraidToForget/p/10116297.html
Copyright © 2020-2023  润新知