ArrayList 中最主要的是扩容机制,因为ArrayList 是非线程安全的,所以当多个线程同时操作时,会导致java.util.ConcurrentModificationException异常
- 新创建的ArrayList对象,如果没有指定长度,则默认为0.
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
- add(E e): 添加元素
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 计算容量的大小
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果初始化的容量大小为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,即为0,则取Math.max(DEFAULT_CAPACITY, minCapacity)之间的最大值,即取DEFAULT_CAPACITY的值,为10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return 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;
// 在原数组的长度的基础上添加1.5 半, oldCapacity >> 1 表示oldCapacity的一半,
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新的长度小于容量长度10,则新数组长度设置为10.
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.
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// 如果大于 MAX_ARRAY_SIZE ,即Integer.MAX_VALUE -8
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}