标签:
1 /** 2 * The array buffer into which the elements of the ArrayList are stored. 3 * The capacity of the ArrayList is the length of this array buffer. 4 */ 5 private transient Object[] elementData; 6 7 /** 8 * The size of the ArrayList (the number of elements it contains). 9 * 10 * @serial 11 */ 12 private int size;
从这里看出, ArrayList是用Array来实现的,包括elementData数组和其大小两个属性。
1 public boolean add(E e) { 2 ensureCapacity(size + 1); // Increments modCount!! 3 elementData[size++] = e; 4 return true; 5 }
/** * 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); } }
ensureCapacity ensure that the inner array size satisfy the add(Object o) operation. If minCapacity is bigger than the original array size, it increase the array size and do the checking again. ensureCapacity() will increase the array size by at least 1. After the array size is OK, copy original array into new array with bigger size. After ensureCapacity() is returned, set elementData[size] to be the newly added element. Since the array size is increased by at least one. call elementData[size] will not throw exception.
标签:
原文地址:http://www.cnblogs.com/touchdown/p/5142286.html