LinkedList源码解析(JDK1.7)

时间:2021-09-20 17:17:24

LinkedList底层使用双向链表数据结构,没有容量大小限制,下面进入源码解析:

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

通过上面这段类的声明:
实现了List接口,可以进行队列操作,实现了Deque接口可以当作双端队列使用,可以克隆,可以序列化
这里JDK1.7中的源码中参数定义和构造函数相比1.6中有了些许变化,LinkedList不再是循环链表,分别用first和last来存储首尾节点。

    transient int size = 0;

/**
* Pointer to first node.
*/

transient Node<E> first;

/**
* Pointer to last node.
*/

transient Node<E> last;

/**
* Constructs an empty list.
*/

public LinkedList() {
}

/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*/

public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}

在首节点前面增加节点:

    private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}

在末节点后面增加节点:

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

在具体一个节点前面插入节点:

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

如果输入是具体的节点,我们会发现插入操作会很便捷。

    /**
* Unlinks non-null first node 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;
}

/**
* Unlinks non-null last node 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; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}

/**
* Unlinks non-null node x.
*/

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;
size--;
modCount++;
return element;
}

同理,入参是具体节点时,删除操作速度也很快。

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

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

//这里是方便用户使用,增加了一层方法调用
public void addFirst(E e) {
linkFirst(e);
}
//同上
public void addLast(E e) {
linkLast(e);
}
    //这里contain方法和ArrayList中一定均是遍历查找,效率较差
public boolean contains(Object o) {
return indexOf(o) != -1;
}
    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;
}
    //虽然在链表中没有索引概念,但可以通过size大小和遍历查找找到元素,效率较低
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
//这里在初始用了一次二分查找
Node<E> node(int 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;
}
}
    //set本质是也是找到index处元素进行替换,同上
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
    //这里的add方法,相比ArrayList的add的数组拷贝只需要断开链接,插入一个元素。
public void add(int index, E element) {
checkPositionIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));//这里慢在node(index),慢在寻址
}

下面是LinkedList作为队列和双端队列使用的方法介绍,不再过多解释:

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

/**
* Retrieves, but does not remove, the head (first element) of this list.
*/

public E element() {
return getFirst();
}

/**
* Retrieves and removes the head (first element) of this list.
*/

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

/**
* Retrieves and removes the head (first element) of this list.
*/

public E remove() {
return removeFirst();
}

/**
* Adds the specified element as the tail (last element) of this list.
*/

public boolean offer(E e) {
return add(e);
}

// Deque operations
/**
* Inserts the specified element at the front of this list.
*/

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

/**
* Inserts the specified element at the end of this list.
*/

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

/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*/

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

/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*/

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

/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*/

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

/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*/

public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
    //Stack operation,前面的peek方法,当作Stack时也可以使用
public void push(E e) {
addFirst(e);
}

/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*/

public E pop() {
return removeFirst();
}
    //这里是浅克隆,只是复制了元素的引用
public Object clone() {
LinkedList<E> clone = superClone();

// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;

// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);

return clone;
}

LinkedList总结:
1.排列有序,不可重复
2.底层实用双向链表数据结构
3.查询速度慢,增删快。
这里查询速度慢是确定,相对于ArrayList的索引直接查找到目标元素,LinkedList需要进行遍历操作。
在增加删除上面有待商榷:
通过源码我们可以看到,如果我们入参直接是一个具体的节点,包含前后引用地址,速度一定很快,但更多的时候,我们都是给一个索引来查找我们需要的元素,
这里LinkedList慢在寻址,需要遍历操作,快在只需要改变前后Node的引用地址。
而ArrayList在插入和删除上,慢在数组元素批量的copy,快在寻址。
所以,如果待插入、删除的元素是在数据结构的前半段尤其是非常靠前的位置的时候,LinkedList的效率将大大快过ArrayList,因为ArrayList将批量copy大量的元素;越往后,对于LinkedList来说,因为它是双向链表,所以在第2个元素后面插入一个数据和在倒数第2个元素后面插入一个元素在效率上基本没有差别,但是ArrayList由于要批量copy的元素越来越少,操作速度必然追上乃至超过LinkedList。
一般而言,ArrayList的数组扩容和数组复制均特别耗时,同时LinkedList在增删上稳定性也强些,综合而言,LinkedList在增删上表现优异些。
4.线程不安全。