ArrayList自动扩容

ArrayList是基于数组实现的

/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */
    private transient Object[] elementData;

    /** * The size of the ArrayList (the number of elements it contains). * * @serial */
    private int size;

构造函数源码:

 /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @exception IllegalArgumentException if the specified initial capacity * is negative */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }

    /** * Constructs an empty list with an initial capacity of ten. */
    public ArrayList() {
        this(10);
    }

在默认情况下,new ArrayList()会初始化一个长度为10的数组。

add方法源码:

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

当增加元素时,会先调用ensureCapacity方法,从方法名可以看出这是一个维护ArrayList容量的方法

ensureCapacity()源码

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

如果当前容量不满足要求时,会调用Arrays.copyOf方法来重置容器

Arrays.copyOf源码:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    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;
}

Arrays.copyOf会创建一个新的数组,并copy原来的数据。

你可能感兴趣的:(ArrayList,自动扩容)