这里只理解主要的常用方法:
1 public class ArrayList<E> extends AbstractList<E>
2 implements List<E>, RandomAccess, Cloneable, java.io.Serializable
3 {
4 private static final long serialVersionUID = 8683452581122892189L;
5
6 /**
7 * 默认的初始化数组容量为10
8 */
9 private static final int DEFAULT_CAPACITY = 10;
10
11 /**
12 * 为空实例使用的共享空数组实例
13 */
14 private static final Object[] EMPTY_ELEMENTDATA = {};
15
16 //用来和EMPTY_ELEMENTDATA区分,EMPTY_ELEMENTDATA是指定容量为0时的,DEFAULTCAPACITY_EMPTY_ELEMENTDATA是没有指定容量时的数组
17
18 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
19
20 /**
21 * 数组缓冲区存放的是ArrayList存储的内容,ArrayList的容量是数组缓冲区的长度,
22 * 当第一次添加元素时如果为空DEFAULTCAPACITY_EMPTY_ELEMENTDATA,容量会被扩展为DEFAULT_CAPACITY;
23 */
24 transient Object[] elementData;
25
26 //指定容量
27
28 public ArrayList(int initialCapacity) {
29 if (initialCapacity > 0) {
30 this.elementData = new Object[initialCapacity];
31 } else if (initialCapacity == 0) {
32 this.elementData = EMPTY_ELEMENTDATA;
33 } else {
34 throw new IllegalArgumentException("Illegal Capacity: "+
35 initialCapacity);
36 }
37 }
38
39 //不指定容量
40
41 public ArrayList() {
42 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
43 }
44
45 /**
46 * 添加数据到list的末尾
47 *
48 * @param e element to be appended to this list
49 * @return <tt>true</tt> (as specified by {@link Collection#add})
50 */
51 public boolean add(E e) {
52 ensureCapacityInternal(size + 1); // Increments modCount!!
53 elementData[size++] = e;
54 return true;
55 }
56
57 //如果出是数组为空并且是第一次添加数据,设置数组容量为默认容量10
58
59 private void ensureCapacityInternal(int minCapacity) {
60 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
61 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
62 }
63
64 ensureExplicitCapacity(minCapacity);
65 }
66
67 //设置容量增长算法
68
69 private void ensureExplicitCapacity(int minCapacity) {
70 modCount++;
71
72 // overflow-conscious code
73 if (minCapacity - elementData.length > 0)
74 grow(minCapacity);
75 }
76
77 /**
78 * 增加容量确保能够容纳至少为给定的最小容量
79 *
80 * @param 需要的最小容量
81 */
82 private void grow(int minCapacity) {
83 // overflow-conscious code
84 int oldCapacity = elementData.length;
85
86 //设置新的容量为原来的1.5倍
87 int newCapacity = oldCapacity + (oldCapacity >> 1);
88
89 //这种情况对应没有指定容量时,添加数据小于默认容量
90 if (newCapacity - minCapacity < 0)
91 newCapacity = minCapacity;
92
93 //容量不能超过指定的最大容量Integer.MAX_VALUE - 8;
94 if (newCapacity - MAX_ARRAY_SIZE > 0)
95 newCapacity = hugeCapacity(minCapacity);
96 // minCapacity is usually close to size, so this is a win:
97
98 //复制新的数组到原来的数组中
99 elementData = Arrays.copyOf(elementData, newCapacity);
100 }
101
102 }