ArrayList源码解析

ArrayList 实现了 List 接口,意味着可以插入空值,也可以插入重复的值,非同步 ,它是基于数组 的一个实现。本文分析基于jdk1.7~

先看其变量部分,对ArrayList的操作本质上是对其底层对象数组的更改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24



//默认初始化数组大小

private static final int DEFAULT_CAPACITY = 10;



//空数组

private static final Object[] EMPTY_ELEMENTDATA = {};



//存放数组的地方

transient Object[] elementData; // non-private to simplify nested class access



//数组长度

private int size;
  1. add方法
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

public boolean add(E e) {

//数组扩容

ensureCapacityInternal(size + 1); // Increments modCount!!

//数组原长度+1的索引位置存放新添加的元素

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;

//数组扩容:10 15 22 33.....每次扩容其长度增加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;

}