Collection - LinkedList源码解析

概述

LinkedList同时实现了 List 接口和 Deque 接口,也就是说它既可以看作一个 顺序容器,又可以看作一个队列(Queue),同时又可以看作一个栈(Stack)

这样看来,LinkedList 简直就是个全能冠军。当你需要使用栈或者队列时,可以考虑使用 LinkedList,一方面是因为 Java 官方已经声明不建议使用 Stack 类,更遗憾的是,Java里根本没有一个叫做 Queue 的类(它是个接口名字)。关于栈或队列,现在的首选是ArrayDeque,它有着比 LinkedList (当作栈或队列使用时)有着更好的性能.

1649409919862

LinkedList 的实现方式决定了所有跟下标相关的操作都是 线性时间,而在 首段 或者 末尾 删除元素只需要常数时间。为追求效率 *LinkedList* 没有实现同步 (synchronized),如果需要多个线程并发访问,可以先采用Collections.synchronizedList()方法对其进行包装。

LinkedLists实现

底层数据结构

LinkedList 底层 通过双向链表实现。双向链表的每个节点用内部类 Node 表示。LinkedList 通过 firstlast 引用分别指向链表的 第一个最后一个 元素。注意这里没有所谓的哑元,当链表为空的时候firstlast都指向null

1
2
3
4
5
transient int size = 0;

transient Node<E> first;

transient Node<E> last;

其中Node是私有的内部类:

1
2
3
4
5
6
7
8
9
10
11
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;

Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}

构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 无参 构造
*/
public LinkedList() {
}

/**
* 构造一个包含了指定集合的列表 ,它们将通过集合的迭代有次序的被返回
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}

getFirst(), getLast()

获取第一个元素, 和获取最后一个元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}

public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}

removeFirest(), removeLast(), remove(e), remove(index)

remove() 方法也有两个版本,一个是删除跟指定元素相等的第一个元素 remove(Object o) ,另一个是删除指定下标处的元素 remove(int index)

1649410993630

删除元素 - 指的是删除第一次出现的这个元素, 如果没有这个元素,则返回 false ;判断的依据是 equals 方法, 如果 equals ,则直接 unlink 这个 node ;由于 LinkedList 可存放null元素,故也可以删除第一次出现null的元素;

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

public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}

E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;

if (prev == null) {// 第一个元素
first = next;
} else {
prev.next = next;
x.prev = null;
}

if (next == null) {// 最后一个元素
last = prev;
} else {
next.prev = prev;
x.next = null;
}

x.item = null; // GC回收
size--;
modCount++;
return element;
}

remove(int index) 使用的是下标计数, 只需要判断该index是否有元素即可,如果有则直接 unlink 这个node。

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
public E remove(int index) {
checkElementIndex(index);// 检测索引是否合法
return unlink(node(index));
}

private void checkElementIndex(int index) {
if (!isElementIndex(index)) // 检测索引是否在 0 - size 之间
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
*
*获取 index 位置的 node 节点
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) { //如果 当前索引在 前半部分
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {//如果 当前索引在 后半部分
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}

删除 head 元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}

private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // 提醒 GC 回收
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}

删除 last 元素:

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

public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}

private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // 提醒 GC 回收
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}

add()

add() 方法有两个版本,一个是 add(E e),该方法在 LinkedList 的末尾插入元素,因为有 last 指向链表末尾,在末尾插入元素的花费是常数时间。只需要简单修改几个相关引用即可;另一个是 add(int index, E element),该方法是在指定下表处插入元素,需要先通过线性查找找到具体位置,然后修改相关引用完成插入操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public boolean add(E e) {
linkLast(e);
return true;
}

void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}

1649412246589

add(int index, E element), 当index==size时,等同于add(E e); 如果不是,则分两步: 1.先根据index找到要插入的位置,即node(index)方法;2.修改引用,完成插入操作。

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

public void add(int index, E element) {
checkPositionIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}

void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}

addAll()

addAll(index, c) 实现方式并不是直接调用add(index,e)来实现,主要是因为效率的问题,另一个是fail-fast中modCount只会增加1次;

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
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);

Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;

Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}

for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}

if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}

size += numNew;
modCount++;
return true;
}

clear()

为了让 GC 更快可以回收放置的元素,需要将node之间的引用关系赋空。

1
2
3
4
5
6
7
8
9
10
11
12
13

public void clear() {
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}

Positional Access 方法

通过index获取元素

1
2
3
4
5

public E get(int index) {
checkElementIndex(index);
return node(index).item;
}

将某个位置的元素重新赋值:

1
2
3
4
5
6
7
8

public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}

将元素插入到指定index位置:

1
2
3
4
5
6
7
8
9

public void add(int index, E element) {
checkPositionIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}

删除指定位置的元素:

1
2
3
4
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}

其它位置的方法 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}

private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}

private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

查找操作

查找操作的本质是查找元素的下标:

查找第一次出现的index, 如果找不到返回-1;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}

查找最后一次出现的 index , 如果找不到返回-1;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}

Queue 方法

先进先出

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
   
/**
* 获取 第一个元素 (不会报错)
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}

/**
* 获取 第一个元素
* 与 peek() 的区别是 element() 抛出了异常 ,若列表为空 则报错
*/
public E element() {
return getFirst();
}

/**
* 删除 首节点
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}

/**
* 删除 首节点
* 与 poll() 的区别是 remove() 抛出了异常 ,若列表为空 则报错
*/
public E remove() {
return removeFirst();
}

/**
* 添加元素至 列表尾部
*/
public boolean offer(E e) {
return add(e);
}

Deque 方法

双端队列

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

public boolean offerFirst(E e) {
addFirst(e);
return true;
}

public boolean offerLast(E e) {
addLast(e);
return true;
}


public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}


public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}

public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}

public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}

//压栈
public void push(E e) {
addFirst(e);
}

//弹出
public E pop() {
return removeFirst();
}

//删除列表中首次出现的元素
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}

//删除列表中最后一次次出现的元素
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}