一、先看下ArrayList的构造方法源码
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity];}public ArrayList() { this(10);}由上面的源码可知,当我们新建一个ArrayList对象的时候:
1、如果我们不指定ArrayList的长度,会默认分配长度为10。
2、ArrayList的底层是一个对象数组。
二、添加元素源码
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true;}private void ensureCapacityInternal(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity);}private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity);}由添加元素源码可知:
1、首先判断容量是否已经满了,如果满了就会扩容,否则的话就将元素放到对象数组里。