ArrayList是List接口的可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。
每个ArrayList实例都有一个容量,该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向ArrayList中不断添加元素,其容量也自动增长。自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造ArrayList时指定其容量。在添加大量元素前,应用程序也可以使用ensureCapacity操作来增加ArrayList实例的容量,这可以减少递增式再分配的数量。
注意,此实现不是同步的。如果多个线程同时访问一个ArrayList实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。
java集合框架示意图如下:

其中ArrayList与Collection的关系:

ArrayList的继承关系如下:
- java.lang.Object
- ↳ java.util.AbstractCollection
- ↳ java.util.AbstractList
- ↳ java.util.ArrayList
-
- public class ArrayList extends AbstractList
- implements List, RandomAccess, Cloneable, java.io.Serializable {}
ArrayList继承了AbstractList,实现了List。它是一个数组队列,相当于动态数组。提供了相关的添加、删除、修改和遍历等功能。
ArrayList实现了RandomAccess接口,即提供了随机访问功能。RandomAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号来快速获取元素对象,这就是快速随机访问。下文会比较List的“快速随机访问”和使用“Iterator迭代器访问”的效率。
ArrayList实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
ArrayList实现了java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
和Vector不同,ArrayList中的操作是非线程安全的。所以建议在单线程中使用ArrayList,在多线程中选择Vector或者CopyOnWriteArrayList。
我们先总览下ArrayList的构造函数和API
-
-
- ArrayList()
-
-
- ArrayList(int capacity)
-
-
- ArrayList(Collection extends E> collection)
-
-
-
- boolean add(E object)
- boolean addAll(Collection extends E> collection)
- void clear()
- boolean contains(Object object)
- boolean containsAll(Collection> collection)
- boolean equals(Object object)
- int hashCode()
- boolean isEmpty()
- Iterator iterator()
- boolean remove(Object object)
- boolean removeAll(Collection> collection)
- boolean retainAll(Collection> collection)
- int size()
- T[] toArray(T[] array)
- Object[] toArray()
-
- void add(int location, E object)
- boolean addAll(int location, Collection extends E> collection)
- E get(int location)
- int indexOf(Object object)
- int lastIndexOf(Object object)
- ListIterator listIterator(int location)
- ListIterator listIterator()
- E remove(int location)
- E set(int location, E object)
- List subList(int start, int end)
-
- Object clone()
- void ensureCapacity(int minimumCapacity)
- void trimToSize()
- void removeRange(int fromIndex, int toIndex)
ArrayList包含了两个重要的对象:elementData和size。
elementData是Object[]类型的数组,它保存了添加到ArrayList中的元素。实际上,elementData是一个动态数组,我们能通过ArrayList(int initialCapacity)来执行它的初始容量为initialCapacity。如果通过不含参数的构造函数来创建ArrayList,则elementData是一个空数组(后面会调整其大小)。elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体见下面的源码。
size则是动态数组实际的大小。
ArrayList的实现:
对于ArrayList而言,它实现List接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。下面我们来分析ArrayList的源代码:
1) 底层使用数组实现:
- private transient Object[] elementData;
2) 构造方法:
ArrayList提供了三种方式的构造器,可以构造一个默认初始容量为10的空列表、构造一个指定初始容量的空列表以及构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。
- public ArrayList() {
- this(10);
- }
-
- public ArrayList(int initialCapacity) {
- super();
- if (initialCapacity < 0)
- throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
- this.elementData = new Object[initialCapacity];
- }
-
- public ArrayList(Collection extends E> c) {
- elementData = c.toArray();
- size = elementData.length;
-
- if (elementData.getClass() != Object[].class)
- elementData = Arrays.copyOf(elementData, size, Object[].class);
- }
3) 存储:
ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection extends E> c)、addAll(int index, Collection extends E> c)这些添加元素的方法。下面我们一一讲解:
-
- public E set(int index, E element) {
- RangeCheck(index);
-
- E oldValue = (E) elementData[index];
- elementData[index] = element;
- return oldValue;
- }
-
- public boolean add(E e) {
- ensureCapacity(size + 1);
- elementData[size++] = e;
- return true;
- }
-
-
- public void add(int index, E element) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
-
- ensureCapacity(size+1);
-
-
-
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = element;
- size++;
- }
-
- public boolean addAll(Collection extends E> c) {
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacity(size + numNew);
- System.arraycopy(a, 0, elementData, size, numNew);
- size += numNew;
- return numNew != 0;
- }
-
- public boolean addAll(int index, Collection extends E> c) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException(
- "Index: " + index + ", Size: " + size);
-
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacity(size + numNew);
-
- 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;
- }
4) 读取:
-
- public E get(int index) {
- RangeCheck(index);
-
- return (E) elementData[index];
- }
5) 删除:
ArrayList提供了根据下标或者指定对象两种方式的删除功能。如下:
-
- public E remove(int index) {
- RangeCheck(index);
-
- modCount++;
- E oldValue = (E) elementData[index];
-
- int numMoved = size - index - 1;
- if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index, numMoved);
- elementData[--size] = null;
-
- 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;
- }
注意:从数组中移除元素的操作,也会导致被移除的元素以后的所有元素的向左移动一个位置。
6) 调整数组容量:
从上面介绍的向ArrayList中存储元素的代码中,我们看到,每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。
- public void ensureCapacity(int minCapacity) {
- modCount++;
- int oldCapacity = elementData.length;
- if (minCapacity > oldCapacity) {
- Object oldData[] = elementData;
- int newCapacity = (oldCapacity * 3)/2 + 1;
- if (newCapacity < minCapacity)
- newCapacity = minCapacity;
-
- elementData = Arrays.copyOf(elementData, newCapacity);
- }
- }
从上述代码中可以看出,数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的1.5倍。这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通过调用ensureCapacity方法来手动增加ArrayList实例的容量。
ArrayList还给我们提供了将底层数组的容量调整为当前列表保存的实际元素的大小的功能。它可以通过trimToSize方法来实现。代码如下:
- public void trimToSize() {
- modCount++;
- int oldCapacity = elementData.length;
- if (size < oldCapacity) {
- elementData = Arrays.copyOf(elementData, size);
- }
- }
7) Fail-Fast机制:
ArrayList也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。
.ArrayList遍历方式
ArrayList支持三种遍历方式,下面我们逐个讨论:
1). 通过迭代器遍历。即Iterator迭代器。
- Integer value = null;
- Iterator it = list.iterator();
- while (it.hasNext()) {
- value = (Integer)it.next();
- }
2). 随机访问,通过索引值去遍历。由于ArrayList实现了RandomAccess接口,所以它支持通过索引值去随机访问元素。
- Integer value = null;
- int size = list.size();
- for (int i = 0; i < size; i++) {
- value = (Integer)list.get(i);
- }
3). 通过for循环遍历。
- Integer value = null;
- for (Integer integ : list) {
- value = integ;
- }
下面写了一个测试用例,比较这三种遍历方式的效率:
- import java.util.*;
-
-
-
-
-
- public class ArrayListRandomAccessTest {
-
- public static void main(String[] args) {
- List list = new ArrayList();
- for (int i=0; i<500000; i++)
- list.add(i);
- isRandomAccessSupported(list);
- iteratorThroughRandomAccess(list) ;
- iteratorThroughIterator(list) ;
- iteratorThroughFor(list) ;
-
- }
-
- private static void isRandomAccessSupported(List list) {
- if (list instanceof RandomAccess) {
- System.out.println("RandomAccess implemented!");
- } else {
- System.out.println("RandomAccess not implemented!");
- }
-
- }
-
- public static void iteratorThroughRandomAccess(List list) {
-
- long startTime;
- long endTime;
- startTime = System.currentTimeMillis();
- for (int i=0; i
- list.get(i);
- }
- endTime = System.currentTimeMillis();
- long interval = endTime - startTime;
- System.out.println("RandomAccess遍历时间:" + interval+" ms");
- }
-
- public static void iteratorThroughIterator(List list) {
-
- long startTime;
- long endTime;
- startTime = System.currentTimeMillis();
- for(Iterator it = list.iterator(); it.hasNext(); ) {
- it.next();
- }
- endTime = System.currentTimeMillis();
- long interval = endTime - startTime;
- System.out.println("Iterator遍历时间:" + interval+" ms");
- }
-
-
- @SuppressWarnings("unused")
- public static void iteratorThroughFor(List list) {
-
- long startTime;
- long endTime;
- startTime = System.currentTimeMillis();
- for(Object obj : list)
- ;
- endTime = System.currentTimeMillis();
- long interval = endTime - startTime;
- System.out.println("For循环遍历时间:" + interval+" ms");
- }
- }
每次执行的结果会有一点点区别,在这里我统计了6次执行结果,见下表:
|
RandomAccess(ms) |
Iterator(ms) |
For(ms) |
第一次 |
5 |
8 |
7 |
第二次 |
4 |
7 |
7 |
第三次 |
5 |
8 |
10 |
第四次 |
5 |
7 |
6 |
第五次 |
5 |
8 |
7 |
第六次 |
5 |
7 |
6 |
平均 |
4.8 |
7.5 |
7.1 |
由此可见,遍历ArrayList时,使用随机访问(即通过索引号访问)效率最高,而使用迭代器的效率最低。
toArray()异常问题
当我们调用ArrayList中的toArray()方法时,可能会遇到"java.lang.ClassCastException"异常的情况,下面来讨论下出现的原因:
ArrayList中提供了2个toArray()方法:
- Object[] toArray()
- T[] toArray(T[] contents)
调用toArray()函数会抛出"java.lang.ClassCastException"异常,但是调用toArray(T[] contents)能正常返回T[]。toArray()会抛出异常是因为toArray()返回的是Object[]数组,将Object[]转换为其它类型(比如将Object[]转换为Integer[])则会抛出"java.lang.ClassCastException"异常,因为java不支持向下转型。解决该问题的办法是调用 T[] toArray(T[] contents),而不是Object[] toArray()。
调用 T[] toArray(T[] contents)返回T[]可以通过以下几种方式实现:
-
- public static Integer[] vectorToArray1(ArrayList v) {
- Integer[] newText = new Integer[v.size()];
- v.toArray(newText);
- return newText;
- }
-
-
- public static Integer[] vectorToArray2(ArrayList v) {
- Integer[] newText = (Integer[])v.toArray(new Integer[v.size()]);
- return newText;
- }
-
-
- public static Integer[] vectorToArray3(ArrayList v) {
- Integer[] newText = new Integer[v.size()];
- Integer[] newStrings = (Integer[])v.toArray(newText);
- return newStrings;
- }
三种方式都大同小异。转自:http://zhangshixi.iteye.com/blog/674856
同时参考:http://blog.csdn.net/eson_15/article/details/51121833