JDK源码——ArrayList源码

本文基于JDK1.8

0x 00 总体描述

ArrayList是基于数组实现的,并且支持自动扩容,相对于普通数组而言,由于他自动扩容的的特性,在日常开发过程中,使用的十分多。
类图

1
2
3
4
// ArrayList.java
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, java.io.Serializable
{

从类图和源码可知,ArrayList实现了四个接口:
java.util.List 接口,主要数组的接口类,提供数组的基本操作,如添加、删除、修改、遍历;
java.util.RandomAccess 接口,提供快速随机访问的能力。
java.io.Serializable 接口,表示ArrayList可序列化。
java.lang.Cloneable 表示其支持克隆
继承了java.util.AbstractList 抽象类,是List接口的基本实现,减少了具体实现类中的大部分共性代码的实现。

注:ArrayList重写了大部分AbstractList的方法实现,所以其对ArrayList作用不大,主要是其他减少了其他子类的实现。

0x01 源码阅读
属性

ArrayList的属性很少,只有两个,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ArrayList.java
/**
* 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

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
* 已使用的数组大小
*/
private int size;

elementData 属性:元素数组,存储元素。
size属性:数组的大小。size表示的是elementData数组存储的元素数量,并且正好是元素添加到数组中的下标,ArrayList的真实大小是elementData的大小。

构造方法

ArrayList一共三个构造方法如下:
#ArrayList(int initialCapacity)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 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) {
// 初始容量大于0 创建Object数组
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
// 等于0 使用其自身的final空数组EMPTY_ELEMENTDATA
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
// 小于0 则抛出参数不合法异常
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}

该构造方法可以根据传入的初始化容量大小,创建对应的ArrayList数组。对于我们已经明确知道容量大小的场景,可以使用这个构造方法,可以减少数组的扩容,提高系统的性能,合理使用内存。’

#ArrayList()
无参构造方法,是我们使用最多的构造方法。

1
2
3
4
5
6
7
8
// ArrayList.java
/**
* Constructs an empty list with an initial capacity of ten.
* 默认容量为10
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

此处需要注意的是,创建的是为空的数组,为了节约内存,在初始化时为空数组,在添加第一个元素时,会真正初始化为10的数组。至于为什么要和EMPTY_ELEMENTDATA区分开来呢,是为区分起点,空数组是从0开始按照1.5呗倍扩容,而不是10,而DEFAULTCAPACITY_EMPTY_ELEMENTDATA首次扩容为10;
#ArrayList(Collection<? extends E> c)
从参数类型可以看出,传的参数为集合类型,作为elementData。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//ArrayList.java
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
// 转换为数组
elementData = c.toArray();
// 判断数组长度
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
// 转化为数组时,可能不是Object类型,则会创建新的Object数组,并赋值给elementData
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
// 若数组大小等于0则直接赋值空数组
this.elementData = EMPTY_ELEMENTDATA;
}
}
普通方法

① 扩容与缩容方法

#trimToSize()

数组的手动缩容方法,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ArrayList.java
**
* Trims the capacity of this <tt>ArrayList</tt> instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an <tt>ArrayList</tt> instance.
*/
public void trimToSize() {
// 记录修改次数
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
// 大小为0则使用空数组
? EMPTY_ELEMENTDATA
// 大于0则创建大小为size的新数组,将原数组复制进去
: Arrays.copyOf(elementData, size);
}
}

#grow()

扩容方法,在扩容过程中,首先创建一个新的更大的数组,一般时1.5倍大小,将原数组复制到新数组中,最后返回新数组。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
ArrayList.java
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;

if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;

// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 1.5的大小 扩容
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;
}

② 查找指定元素对应的下标

#indexOf(Object o)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ArrayList.java
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index
*/
public int indexOf(Object o) {
// 判断元素是否为null
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
// 非null使用equals判断全等,比较的是对象是否相等
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}

③ 克隆方法

#clone()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ArrayList.java
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
// 调用父类的克隆方法
ArrayList<?> v = (ArrayList<?>) super.clone();
// 将原数组拷贝进新数组
// 此处的数组是新拷贝出来的,避免和原数组共享引用
v.elementData = Arrays.copyOf(elementData, size);
// 设置修改次数为0
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}

④ 转换为数组

#toArray() and #toArray(T[] a)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// ArrayList.java
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
// 此方法返回是Object[]
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 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.
*
* <p>If the list fits in the specified array with room to spare
* (i.e., the array has more elements than the list), the element in
* the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of the
* list <i>only</i> if the caller knows that the list does not contain
* any null elements.)
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
//
public <T> T[] toArray(T[] a) {
// 若传入的数组大小小于size的大小
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
// 复制返回一个新数组
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
// 将elementData复制到a
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
// 返回a
return a;
}

由于可能返回新的数组,所以这里建议使用时还是这么写:a = list.toArray(a)

⑤ 获取指定位置元素

#get(int index)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ArrayList.java
E elementData(int index) {
return (E) elementData[index];
}

/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
// 下标检查 index 不能超过size
rangeCheck(index);
return elementData(index);
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

⑥ 设置指定位置元素

#set(int index, E element)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// ArrayList.java
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
// 下标检验
rangeCheck(index);
// 获取下标的原数据
E oldValue = elementData(index);
// 对应下标设置新元素
elementData[index] = element;
// 返回老值
return oldValue;
}

⑦ 添加单个元素

#add(E e)

顺序添加某个元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// ArrayList.java

/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
// 扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 将新建的元素添加到末尾
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
// 增加数组的修改次数
modCount++;

// overflow-conscious code
// 数组扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}

#add(int index, E element)

在某个确定位置添加元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ArrayList.java
/**
* 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).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
// 范围检查
rangeCheckForAdd(index);
// 数组扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 数组元素拷贝 空出index位置
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 对应位置赋值
elementData[index] = element;
// size增加1
size++;
}

⑧ 移除元素

#remove(int index)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ArrayList.java
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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);
// clear to let GC do its work
elementData[--size] = null;

return oldValue;
}