java 扩容

private void ensureCapacity(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - buf.length > 0)
            grow(minCapacity);
    }

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 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 = buf.length;
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
     
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        buf = Arrays.copyOf(buf, newCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
  • 扩容操作理想情况是将容积增加为原来的2倍

  • newCapacity=Math.max(oldCapacity*2,minCapacity) 确保扩容后的数组大于等于minCapacity,扩容的意义就是增大容量嘛

  • newCapacity大于MAX_ARRAY_SIZE,调用hugeCapacity, 这里对newCapacity根据minCapacity做一个微调,如果minCapacity>MAX_ARRAY_SIZE,那么newCapacity=Integer.MAX_VALUE,否则newCapacity=MAX_ARRAY_SIZE
    这么做的理由是因为不同的JVM实现上可能运行分配的最大字节数组稍微小于Integer.MAX_VALUE,但是MAX_ARRAY_SIZE这个值对于所有的JVM来说都是ok的,所以尽量让数组长度不要达到Integer.MAX_VALUE,除非必须要这么做

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容