Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ensureCapacity方法存在的意义在哪? #35

Closed
changchangjie opened this issue Oct 10, 2018 · 1 comment
Closed

ensureCapacity方法存在的意义在哪? #35

changchangjie opened this issue Oct 10, 2018 · 1 comment
Labels
question Further information is requested

Comments

@changchangjie
Copy link

对于ArrayList添加大量元素,最好调用ensureCapacity方法进行提前扩容,为啥不直接用有参构造方法呢,这个方法存在的意义在哪呢?

@Snailclimb
Copy link
Owner

ensureCapacity()方法的源码如下:

/**
      *如有必要,增加此ArrayList实例的容量,以确保它至少可以容纳由minimum capacity参数指定的元素数。
     *
      * @param minCapacity所需的最小容量(也就是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);
        }
    }

@Snailclimb Snailclimb added the question Further information is requested label Mar 3, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants