ArrayList扩容机制探究
作者:互联网
一、ArrayList扩容机制探究
1.1 成员变量
//默认初始容量
private static final int DEFAULT_CAPACITY = 10;
//空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
//空数组,用于默认初始容量的,扩容时会使用
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//存放数组中的元素
transient Object[] elementData;
//数组元素的个数,区别于elementData.length
private int size;
//
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
1.2 三个构造函数
/*默认的无参构造*/
public ArrayList() {
//空数组,数组长度为0
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/*用户给定初始容量的构造函数*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//用户指定的初始容量大于0,则创建一个指定容量的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//用户指定的初始容量等于0,空数组,数组长度为0
this.elementData = EMPTY_ELEMENTDATA;
} else {
//否则抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
}
}
/*包含特定元素集合的构造函数*/
public ArrayList(Collection<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}
1.3 Add方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,size - index);
elementData[index] = element;
size++;
}
add一个元素的时候,先调用了ensureCapacityInternal方法
private void ensureCapacityInternal(int minCapacity) {
//此时elementData还是空数组,minCapacity=1
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//Math,max(10,1),返回10
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
//minCapacity=10,elementData.length=0,进入grow方法,当add第二个元素时,elementData.length=10,就不满足这个条件了,不会进行扩容,直到添加第11个元素。
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
//旧的容量
int oldCapacity = elementData.length;
//新的容量=旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//检查新容量是否比最小容量还小,还小的话直接将新容量指定为最小容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//新容量大于MAX_ARRAY_SIZE,新容量=hugeCapacity(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);
}
标签:扩容,容量,int,ArrayList,elementData,private,探究,minCapacity,size 来源: https://www.cnblogs.com/wxwcnblog/p/16257221.html