一、类图关系
二、要点记录
1. 与 Vector 功能几乎一样, 但是 ArrayList 是线程不安全的
2. 添加元素前,如果已知要添加元素的数量,调用 ensureCapacity 函数提前准备容量,能降低扩容次数
3. 迭代器 fail-fast
4. ArrayList 默认容量为 10,可以在构造函数中指定容量,没有增长步长参数,直接扩大为原来的1.5倍
当然,如果扩大1.5倍依然盛不下,就直接使用目标容量大小
容量不超过整数范围,否则 抛出 OutOfMemoryError
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}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;
}
5. Clone 和 Vector 差不多,都是属于浅复制
6. sort 与 Vector 一样,调用 Arrays.sort()
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}