Let's look at this code (jdk1.8)
@Test public void testArraySize() throws Exception { List<String> list = new ArrayList<>(); list.add("ds"); list.add("cx"); list.add("cx"); list.add("ww"); list.add("ds"); list.add("cx"); list.add("cx"); list.add("ww"); list.add("ds"); list.add("cx"); list.add("last"); }
1) Put a breakpoint on the line when the "last" is inserted
2) Go to the ArrayList add method. You will see
ensureCapacityInternal(size + 1);
3) Go to the method ensure CapacityInternal, which calls this method ensureExplicitCapacity
four)
private void ensureExplicitCapacity(int minCapacity) { modCount++;
In our example, minCapacity is 11 11-10 > 0 , so you need a grow method
5)
private void grow(int minCapacity) {
Let's describe each step:
1) oldCapacity = 10, because we did not specify this parameter when initializing the ArrayList , so it will use the default capacity (10)
2) int newCapacity = oldCapacity + (oldCapacity >> 1); Here newCapacity is equal to oldCapacity plus oldCapacity with a right shift of one ( oldCapacity is 10 is a binary representation of 00001010 shifting one bit to the right, we get 00000101 , which is 5 in decimal, so newCapacity is 10 + 5 = 15 )
3)
if (newCapacity - minCapacity < 0) newCapacity = minCapacity;
For example, your initialization capacity is 1, when you add the second element to arrayList newCapacity will be 1(oldCapacity) + 0 (moved to right by one bit) = 1 In this case, newCapacity is less than minCapacity and elementData (the array object inside arrayList) cannot contain a new element, so newCapacity is equal to minCapacity
four)
if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity);
Check if the size of the array is MAX_ARRAY_SIZE (which is Integer.MAX - 8) Why is the maximum size of the ArrayList array Integer.MAX_VALUE - 8?
5) Finally, it copies the old values to newArray of length 15