LinkedList 源码解读 基于jdk1.7.0_80

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable

LinkdedList 的底层是 链表结构  ,所以节点的设置很关键

节点类

 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;
}
}

LinkdedList 类属性

    transient int size = 0;
/**
* Pointer to first node.
*/
transient Node<E> first; /**
* Pointer to last node.
*/
transient Node<E> last;

add方法

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++;
}
public void add(int index, E element) {
checkPositionIndex(index); if (index == size)
linkLast(element);
else
     //获取index位置上的节点,然后在这个前插入新节点
linkBefore(element, node(index));
}
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;
}
}
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++;
}

因为实现了 Deque接口,所以有很多队列相关的操作

//获取第一个节点,并删除
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : 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; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
05-11 20:13