Java 容器源码分析之 LinkedList(3)
 
- UID
- 1066743
|

Java 容器源码分析之 LinkedList(3)
移除尾部节点1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
| 移除任意一个非空节点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
| //移除一个非空节点
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; //后继
//注意对前驱为null的处理
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
//注意对后继为null的处理
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null; //GC
size--;
modCount++;
return element;
}
| 清空链表主要是为了方便垃圾回收器进行垃圾回收。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
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++;
} |
|
|
|
|
|
|