基于数组实现的容量可变的非线程安全List。
1)其实现基本与Vector等效,Vector为线程安全的,但是同步效率低,所以基本不用。
2)时间复杂度:size、isEmpty、get、set为O(1);iterator、listIterator遍历所有元素为O(N)(N为容量);add(E e) n个元素为O(n);其他操作一般是线性时间。
3)fail-fast:iterator()、listIterator(int)返回的迭代器为fail-fast的,对于迭代器创建后的结构性修改(除了其自身的ListIterator.remove()、ListIterator.add(Object)操作)会抛出ConcurrentModificationException异常。
采用数组实现:
private transient Object[] elementData;
// 带初始容量参数
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
// 无参构造,后续增加会采用默认容量值DEFAULT_CAPACITY=10
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
// 带Collection参数,将其元素复制过来
public ArrayList(Collection extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
// 基础方法
E elementData(int index) {
return (E) elementData[index];
}
// 末尾增加
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++;
}
// 随机删除
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
// 先查找再删除
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
// 随机修改
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
// 随机访问
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
对于动态增加、删除元素,都用到了arraycopy这个方法来操作:
void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy其实是一个native方法:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
// 提供给外部使用来设置最小容量
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != EMPTY_ELEMENTDATA)
// any size if real element table
? 0
// larger than default for empty table. It's already supposed to be
// at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
// 供内部add、addAll使用,增加元素前需要确保有足够的容量
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(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;
int newCapacity = oldCapacity + (oldCapacity >> 1); // 1.5倍oldCapacity
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);
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
都用到了Arrays.copyOf方法,其最终还是用到了System.arraycopy方法:
public static T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static T[] copyOf(U[] original, int newLength, Class extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
采用AbstractList中的modCount来控制结构性修改:
protected transient int modCount = 0;
private class Itr implements Iterator
private class ListItr extends Itr implements ListIterator
提供Iterator、ListIterator,其中ListIterator可前后遍历,它们的实现都是基于elementData数组实现的,用modCount来控制结构性修改,其中Itr.remove、ListItr.set(E)、ListItr.add(E)都直接用了ArrayList中相应的随机访问方法实现。
从ArrayList的方法中可以看出,其完全利用了数组的特性,随机访问效率高,只不过在涉及动态增加、删除元素时需要用到System.arraycopy来复制移动元素,以及add\addAll时可能需要扩展数组,这一点LinkedList值需要修改next就可以了,但是不妨碍ArrayList的高效使用。