ArrayList.add时增加数组长度

ArrayList内部是使用数组存放数据,在调用add时需要判断数组长度是否够,不够则新增数组长度,新的数数组长度和旧长度的关系为:
int newCapacity = (oldCapacity * 3) / 2 + 1;

public boolean add(E e) {
    ensureCapacity(size + 1); // Increments modCount!!
    elementData[size++] = e;
    return true;
}

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

你可能感兴趣的:(java,ArrayList)