首先,来看下ArrayList中关于容量的代码 /** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access
/** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
/** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
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); }
private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
grow的扩容算法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); 首先,将原来容量(现在数组的长度)扩大为1.5倍。
if (newCapacity - minCapacity < 0) newCapacity = minCapacity; 如果扩大1.5倍后还不够存放新元素。则将新容量设置为需要的容量。 (如果newCapacity溢出, if (newCapacity - minCapacity < 0) 为false 不会走的)