Skip to content

Commit 52451b7

Browse files
committed
ArrayList
1 parent 781defd commit 52451b7

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

MD/ArrayList.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# ArrayList 的底层实现
2+
3+
`ArrayList` 实现于 `List``RandomAccess` 接口。可以插入空数据并且允许数据为空,也支持随机随机访问。
4+
5+
`ArrayList `相当于动态数据,其中最重要的两个属性分别是:
6+
`elementData` 数组,以及 size 大小。
7+
在调用 `add()` 方法的时候:
8+
```java
9+
public boolean add(E e) {
10+
ensureCapacityInternal(size + 1); // Increments modCount!!
11+
elementData[size++] = e;
12+
return true;
13+
}
14+
```
15+
16+
- 首先进行扩容校验。
17+
- 将插入的值放到尾部,并将 size + 1 。
18+
19+
如果是调用 `add(index,e)` 在指定位置添加的话:
20+
```java
21+
public void add(int index, E element) {
22+
rangeCheckForAdd(index);
23+
24+
ensureCapacityInternal(size + 1); // Increments modCount!!
25+
//复制,向后移动
26+
System.arraycopy(elementData, index, elementData, index + 1,
27+
size - index);
28+
elementData[index] = element;
29+
size++;
30+
}
31+
```
32+
33+
34+
- 也是首先扩容校验。
35+
- 接着对数据进行复制,目的是把 index 位置空出来放本次插入的数据,并将后面的数据向后移动一个位置。
36+
37+
其实扩容最终调用的代码:
38+
```java
39+
private void grow(int minCapacity) {
40+
// overflow-conscious code
41+
int oldCapacity = elementData.length;
42+
int newCapacity = oldCapacity + (oldCapacity >> 1);
43+
if (newCapacity - minCapacity < 0)
44+
newCapacity = minCapacity;
45+
if (newCapacity - MAX_ARRAY_SIZE > 0)
46+
newCapacity = hugeCapacity(minCapacity);
47+
// minCapacity is usually close to size, so this is a win:
48+
elementData = Arrays.copyOf(elementData, newCapacity);
49+
}
50+
```
51+
52+
也是一个数组复制的过程。
53+
54+
由此可见 `ArrayList` 的主要消耗是数组扩容以及在指定位置添加数据,在日常使用时最好是指定大小,尽量减少扩容。更要减少在指定位置插入数据的操作。

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Java 面试常见题型
22

33
### Java 基础
4-
4+
ArrayList 底层实现
55

66
### Java 多线程
77
- [多线程中的常见问题](https://github.com/crossoverJie/Java-Interview/blob/master/MD/Thread-common-problem.md)

0 commit comments

Comments
 (0)