Posted onInjava
,
数据结构Valine: Symbols count in article: 714Reading time ≈1 mins.
实质
ArrayList的底层实现就是数组
其动态变化的长度是由其扩容机制所组成的,在jdk1.8中,扩容代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ privatevoidgrow(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); }