1.ArrayList的UML图:
1.1.关于RandomAccess接口
ArrayList实现了RandomAccess接口,此接口为标记接口,表明实现此接口的List实现类具有随机访问特性。一些适用于随机访问列表的的算法应用与顺序访问列表时,可能会有不同的表现。如果一个算法在应用到随机访问列表的性能高于顺序访问列表时,建议检查此接口,并对算法做出相应调整以满足性能需求。
通常,如果循环A比循环B快的时候,就需要实现RandomAccess接口。
循环A:
for (int i=0, n=list.size(); i < n; i++)
list.get(i);
循环B:
for (Iterator i=list.iterator(); i.hasNext(); )
i.next();
2. ArrayList的内部实现:
2.1.数据存储:
ArrayList通过内部维护的一个数组transient Object[] elementData来存储数据。
/**
* 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
2.2.构造方法:
ArrayList有三个构造方法:
2.2.1. 无参构造方法
/**
* 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;
}
使用无参构造方法创建ArrayList时会使用DEFAULTCAPACITY_EMPTY_ELEMENTDATA创建一个空数组,但是此时ArrayList的容量使用的是默认容量10。
2.2.2. 带初始化容量参数的构造方法
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "&