Search code examples
javalistcollectionsbitsetdynamic-allocation

Java Collections automatic reallocation when size is reached


I'm not sure if I'm using the correct terms, but I am curious how it's determined how much to increase the size of a Collection in Java when it gets full? I've tried searching but I'm not really coming up with anything useful.

So, if I have something like


List l = new ArrayList(1);
l.add("1");
l.add("2");
How does it determine how much to increase the size of the list? Is it always a set value and if so, what is that value? I'd also be interested in this information for BitSet if it differs.

Thanks and let me know if I should clarify any.


Solution

  • it calls 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) {
        modCount++;
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3) / 2 + 1;
            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }
    

    so as you can see the newCapacity is the (oldCapacity * 3) / 2 + 1