|
@@ -0,0 +1,44 @@
|
|
1
|
+# ArrayList 无参构造器创建实例
|
|
2
|
+```java
|
|
3
|
+ // 源码:无参构造器
|
|
4
|
+ public ArrayList() {
|
|
5
|
+ this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
|
|
6
|
+ }
|
|
7
|
+ // add
|
|
8
|
+ // 1、先确定是否扩容 2、然后再执行赋值
|
|
9
|
+ public boolean add(E e) {
|
|
10
|
+ ensureCapacityInternal(size + 1); // Increments modCount!!
|
|
11
|
+ elementData[size++] = e;
|
|
12
|
+ return true;
|
|
13
|
+ }
|
|
14
|
+ // 该方法确定最小容量 minCapacity (1)第一次扩容为10
|
|
15
|
+ private void ensureCapacityInternal(int minCapacity) {
|
|
16
|
+ if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
|
|
17
|
+ minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
|
|
18
|
+ }
|
|
19
|
+ ensureExplicitCapacity(minCapacity);
|
|
20
|
+ }
|
|
21
|
+ // 1、modCount++ 记录集合被修改的次数
|
|
22
|
+ // 2、如果 elementData大小不够 就调用grow 扩容
|
|
23
|
+ private void ensureExplicitCapacity(int minCapacity) {
|
|
24
|
+ modCount++;
|
|
25
|
+ // overflow-conscious code
|
|
26
|
+ if (minCapacity - elementData.length > 0)
|
|
27
|
+ grow(minCapacity);
|
|
28
|
+ }
|
|
29
|
+ // 底层真正实现扩容的 方法
|
|
30
|
+ private void grow(int minCapacity) {
|
|
31
|
+ // overflow-conscious code
|
|
32
|
+ int oldCapacity = elementData.length;
|
|
33
|
+ // 右移一位相当于 除以2 新的为 旧的1.5倍
|
|
34
|
+ int newCapacity = oldCapacity + (oldCapacity >> 1);
|
|
35
|
+ if (newCapacity - minCapacity < 0)
|
|
36
|
+ newCapacity = minCapacity;
|
|
37
|
+ if (newCapacity - MAX_ARRAY_SIZE > 0)
|
|
38
|
+ newCapacity = hugeCapacity(minCapacity);
|
|
39
|
+ // minCapacity is usually close to size, so this is a win:
|
|
40
|
+ elementData = Arrays.copyOf(elementData, newCapacity);
|
|
41
|
+ }
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+```
|