类定义
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList继承了AbstractList,实现了List、RandomAccess、Cloneable、Java.io.Serializable接口。从类定义可以看出ArrayList支持泛型,可序列化,并实现了List接口定义的方法。
ArrayList顶着List的皮,实际的数据结构是数组。
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
private transient Object[] elementData;
RandomAccess
ArrayList实现了RandomAccess接口,也意味着ArrayList擅长随机访问、批量处理高效。遍历时,通过下标访问速度更快。相对地,链表擅长遍历、插入、删除,链表使用迭代器迭代高效;
构造函数
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
/**
* Constructs an empty list with the specified initial capacity.
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*/
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);
}
第一个构造方法构造一个大小为0的空数组(jdk1.7,通常执行add方法等后会设置数组大小为10)。
第二个构造方法使用提供的initialCapacity来初始化elementData数组的大小。
第三个构造方法则将提供的集合转成数组返回给elementData(返回若不是Object[]将调用Arrays.copyOf方法将其转为Object[])。
实现的List接口方法
以下列出的方法按照List接口定义顺序阐述:
size()
/**
* Returns the number of elements in this list.
*/
public int size() {
return size;
}
返回私有属性size。
isEmpty()
/**
* Returns <tt>true</tt> if this list contains no elements.
*/
public boolean isEmpty() {
return size == 0;
}
通过size是否为0来判断是否含有元素。
contains(Object o)
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
通过indexOf方法返回值与0比较来判断对象是否在list中。
而indexOf方法通过遍历elementData数组来判断对象是否在list中。若存在则返回最先出现该元素的index,若不存在则返回-1。存在与否是通过equals方法比较,没有重写equals方法就是比较对象地址是否相同。
iterator()
/**
* Returns an iterator over the elements in this list in proper sequence.
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
iterator()方法执行Itr类的默认构造函数,返回一个Iterator<E>
对象。Iterator是Java迭代器最简单的实现,next()获得序列中的下一个元素,hasNext()检查序列中是否还有元素,remove()将迭代器新返回的元素删除。
toArray()
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
调用Arrays.copyOf将返回一个数组,该数组含有elementData中所有的元素。
toArray(T[] a)
/**
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element); the runtime type of the returned
* array is that of the specified array. If the list fits in the
* specified array, it is returned therein. Otherwise, a new array is
* allocated with the runtime type of the specified array and the size of
* this list.
*/
@SuppressWarnings("unchecked")
public <T> 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;
}
若传入数组的长度小于size,则返回一个新的数组,大小为size,类型与传入数组相同。
若传入数组的长度等于size,则将elementData复制到传入数组中并返回传入的数组。
若传入数组的长度大于size,则除了复制elementData外,还将把返回数组的第size个元素置为空。
add(E e)
/**
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
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);
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);
}
我们先看下ensureCapacityInternal方法,从方法名可知,该方法保证数组容量可用。当初次执行add方法,size为0,minCapacity会取默认大小10和传入size:1中的最大值,然后变量modCount(记录list结构被改变的次数)进行自增,minCapacity大于elementData数组长度就会扩容,也就是执行grow方法。
grow方法调整容量newCapacity为min(max((oldCapacity*3)/2+1,minCapacity),MAX_ARRAY_SIZE),返回一个内容为原数组元素、大小为新容量的数组并赋给elementData。这里可以看到,容量的拓展将导致数组元素的复制,多次拓展容量将执行多次整个数组内容的复制。若提前能大致判断list的长度,分配合理的数组容量,将有效提高运行速度。
在保证数组容量可用后,将新增元素添加在数组的size索引位。最后size进行一次自增。
remove(Object o)
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*/
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;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
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
}
当移除成功后返回true,否则返回false。该方法通过遍历elementData寻找是否存在传入对象,一旦找到就调用fastRemove移除对象。fastRemove方法就是将index后的元素全部向前移一位,并将原数组最后一位、索引位size-1的元素置为null。
addAll(Collection<? extends E> c)
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the
* specified collection's Iterator. The behavior of this operation is
* undefined if the specified collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this
* list is nonempty.)
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
与add方法相似,先将集合c转换成数组a,然后调用ensureCapacityInternal方法确保复制前数组容量可用,再调用System.arraycopy方法将a复制到elementData的尾部,最后调整size。根据返回的内容分析,只要集合c的大小不为空,即转换后的数组长度不为0则返回true。
addAll(int index, Collection<? extends E> c)
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
先通过rangeCheckForAdd方法判断index是否越界。其他内容与addAll(Collection<? extends E> c)
基本一致,只是复制时先将index开始的元素向后移动numNew个位置,再将要添加的数组内容复制到elementData的index至index+numNew位置上。
removeAll(Collection<?> c)
/**
* Removes from this list all of its elements that are contained in the
* specified collection.
*/
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
removeAll方法是删除list中包含在集合参数中的元素。删除操作后,数组还剩有元素则返回真,若全部被删除则返回假。通过遍历数组,如果当前元素并不存在于集合对象中,就将该元素存放至elementData数组的前面。变量w用来维护被保留下来元素的个数。可以预见,局部变量r的值只会大于等于变量w的值。
正常情况下,遍历数组完毕后变量r与size的值相等。如果执行contains方法抛出了异常,导致r与size的值不相等,那么未被遍历的元素将被接到数组后面。变量w的值直接加上未处理元素的个数,size - r。
如果变量w与size的值不相等,也就是数组中元素没有被全部删掉,则将索引位置w后的所有元素置为null,等待GC回收该部分堆内存。
retainAll(Collection<?> c)
/**
* Retains only the elements in this list that are contained in the
* specified collection. In other words, removes from this list all
* of its elements that are not contained in the specified collection.
*/
public boolean retainAll(Collection<?> c) {
return batchRemove(c, true);
}
retainAll方法和removeAll方法是反操作,只保留数组中和集合参数中相同的元素。保留操作后,数组还剩有元素则返回真,若全部被删除则返回假。
clear()
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
clear的时候并没有修改elementData的长度,只是将所有元素置为null,size设置为0。
get(int index)
/**
* Returns the element at the specified position in this list.
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
先判断index是否越界,然后返回指定位置的元素。
set(int index, E element)
/**
* Replaces the element at the specified position in this list with
* the specified element.
*/
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
先判断index是否越界,然后替换指定索引处的元素,最后返回被替换前的元素值。
add(int index, E element)
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*/
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++;
}
该方法在指定位置添加元素。具体将先检查index是否越界,然后确保数组容量、必要时将扩容,再将index后的所有元素整体向后移一位,最后把空出来的index索引位留给新添加的元素。
remove(int index)
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*/
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;
}
该方法删除指定位置的元素,并返回该元素。方法首先进行index是否越界的判断,用变量保存待删除元素的引用,然后将index位以后的元素整体向前移一位,空出来的最后一位将置为null,等待GC回收堆内存,最后返回被删除的元素。
lastIndexOf(Object o)
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
和indexOf相反,采用了从后向前遍历elementData数组,若遇到Object则返回其index值,若没有遇到则返回-1。
listIterator()
/**
* Returns a list iterator over the elements in this list (in proper
* sequence).
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* An optimized version of AbstractList.ListItr
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
listIterator()方法执行内部类ListItr的带参构造函数,返回一个ListIterator<E>
对象。
subList(int fromIndex, int toIndex)
/**
* Returns a view of the portion of this list between the specified
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
* {@code fromIndex} and {@code toIndex} are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations.
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
返回一个指定区间的子数组。
ArrayList和Vector的区别
- 数据增长:Vector增长原来的一倍,ArrayList增加原来的0.5倍。
- 同步性:Vector是线程安全的,而ArrayList是线程序不安全的。