ArrayList底层源码

1
2
3
4
5
public abstract class AbstractList<E> extends AbstractCollection<E>implements List<E>{
//外部操作数:记录了数据量变化的次数
//对于数据的更新(添加、删除、清空),modCount就会++
protected transient int modCount = 0;// 2
}
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
public class ArrayList<E> extends AbstractList<E> implements List<E>{
//默认容量
private static final int DEFAULT_CAPACITY = 10;
//数据容器的最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//空内容的数组(长度为0)
private static final Object[] EMPTY_ELEMENTDATA = {};
//默认容量的空内容的数组(长度为0)
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//数据容器
transient Object[] elementData;//new Object[10]{"麻生希","椎名空",....}
//元素个数(指针)
private int size;// 2

public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];//new Object[10000];

} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;//{}

} else {//容量为负数,就报错
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}

//e - 椎名空
public boolean add(E e) {
ensureCapacityInternal(size + 1);

//添加元素
elementData[size++] = e;
return true;
}

//minCapacity - 11
private void ensureCapacityInternal(int minCapacity) {
//使用无参构造创建对象,第一次添加元素时进入
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//minCapacity - 10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}

ensureExplicitCapacity(minCapacity);
}

//minCapacity - 11
private void ensureExplicitCapacity(int minCapacity) {
modCount++;

if (minCapacity - elementData.length > 0)
grow(minCapacity);
}

//minCapacity - 11
private void grow(int minCapacity) {

// oldCapacity - 10
int oldCapacity = elementData.length;
// newCapacity - 15
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)

newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);

// 数组扩容
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;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
public class Test01 {
public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>();
//ArrayList<String> list = new ArrayList<>(10000);

list.add("麻生希");
list.add("椎名空");
list.add("水菜丽");
list.add("朝桐光");
}
}
  1. ArrayList的数据结构是什么?

    Object类型的一维数组

  2. ArrayList默认容量是多少?

    10

  3. ArrayList最大容量是多少?

    Integer.MAX_VALUE-8

  4. ArrayList最大容量为什么是Integer.MAX_VALUE-8?

    -8是为了预留空间去存储数组的头部信息

  5. 如果大量数据需要存入集合,你会怎么办?

    创建集合时,自定义集合长度,减少扩容次数,提高效率

  6. ArrayList的扩容机制是什么?

    是原来数组长度的1.5倍