ArrayList construction method source code analysis, arraylist construction source code
First, let's take a look at the construction method without parameters:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; transient Object[] elementData; public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
If the capacity is not specified for an hour, the final defacapcapacity_empty_elementdata will be sent to elementData. The advantage is that the initial storage object of ArrayList is fixed no matter how many instantiation times, instead of creating a new Object array every time.
In this way, you need to call the method ensureCapacityInternal (int) every time you add an operation ):
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(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); }
Each time you call the add operation, the system will verify whether the capacity is instantiated. Here, DEFAULT_CAPACITY = 10, that is, when the capacity is not specified, the first add operation sets the list capacity to 10.
The modCount attribute is used to save the number of list modification operations. Its value is often used in iterator. It will save its value before traversal. In each next (), remove (), it will go back to compare whether modCount has changed. If it changes, it will throw ConcurrentModificationException.
Grow () is used to increase the list capacity. The second row in this method can also be written:
int newCapacity = oldCapacity * 3 / 2;
However, bitwise operations are much faster than multiplication and division.
The construction method with capacity parameters is much simpler:
public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }