读Java11 源码(2)LinkedList

具体的架构图
在这里插入图片描述

1、 LinkedList的属性

transient int size = 0;
/**
 * 指向头结点
 */
transient Node<E> first;
/**
 * 指向尾结点
 */
transient Node<E> last;

为什么要用transient来修饰?因为序列化这两个属性其实没有意义的,我们知道,序列化的意义就在于要把数据给保存再来,但是链表他是一个节点一个节点的,不是连续存放的,如果你就保存一头一尾两个节点就没有任何意义了,中间的数据要咋办,你序列化后,那些引用就没用了,你不能用next来获取下一个节点了。所以,LinkedList自己写了writeObject、readObject方法来进行序列化和反序列化,可以看到都用了遍历来提取、连接数据。

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

    // Write out size
    s.writeInt(size);

    // Write out all elements in the proper order.
    for (Node<E> x = first; x != null; x = x.next)
        s.writeObject(x.item);
}
private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
    // Read in any hidden serialization magic
    s.defaultReadObject();

    // Read in size
    int size = s.readInt();

    // Read in all elements in the proper order.
    for (int i = 0; i < size; i++)
        linkLast((E)s.readObject());
}

因为链表的构造方法简单的不行,就不说了。

2、Node结构

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

3、增加节点

public void add(int index, E element) {
    checkPositionIndex(index);
    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}
private void checkPositionIndex(int index) {
 	if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
void linkBefore(E e, Node<E> succ) {
	// 先找出当前节点的前一个节点
    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++;
}
 /**
  * 根据索引来找节点
  */
Node<E> node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {  // 先判断给的index是否大于二分之一的size
        Node<E> x = first; // 如果小于,从first开始
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last; // 如果大于,就从last开始找
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

以上这段代码是根据索引找node的代码,先判断给的index是否大于二分之一的size,如果小于二分之一的size,从first开始找;如果大于二分之一的size,从last开始找。

4、删除节点

我们先来看看代码逻辑

/**
 * 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;1if (prev == null) {
        first = next;2} else {
        prev.next = next;3)
        x.prev = null;  // help GC
    }4if (next == null) {
        last = prev;5} else {
        next.prev = prev;6)
        x.next = null;  // help GC
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}

删除代码的逻辑:
(1)先判断是否为头结点,是->(2),否->(3)
(2)first引用直接只想当前节点下一个节点
(3)前一个节点的next引用指向 下一个节点
(4)判断是否为最后一个节点;是->(5),否->(6)
(5)最后的last的引用指向前一个节点
(6)下一个节点的pre 指向前一个节点
因为是双向链表,所以操作更加复杂一点。

5、查询

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

走的其实就在增加模块里就已经讲到的node方法。

6、迭代器

private class ListItr implements ListIterator<E> {
    private Node<E> lastReturned;
    private Node<E> next;
    private int nextIndex;
    private int expectedModCount = modCount;

    ListItr(int index) {
        // assert isPositionIndex(index);
        next = (index == size) ? null : node(index);
        nextIndex = index;
    }

    public boolean hasNext() {
        return nextIndex < size;
    }

    public E next() {
        checkForComodification();
        if (!hasNext())
            throw new NoSuchElementException();

        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }

    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    public E previous() {
        checkForComodification();
        if (!hasPrevious())
            throw new NoSuchElementException();

        lastReturned = next = (next == null) ? last : next.prev;
        nextIndex--;
        return lastReturned.item;
    }

    public int nextIndex() {
        return nextIndex;
    }

    public int previousIndex() {
        return nextIndex - 1;
    }

    public void remove() {
        checkForComodification();
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }

    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();
        lastReturned.item = e;
    }

    public void add(E e) {
        checkForComodification();
        lastReturned = null;
        if (next == null)
            linkLast(e);
        else
            linkBefore(e, next);
        nextIndex++;
        expectedModCount++;
    }

    public void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (modCount == expectedModCount && nextIndex < size) {
            action.accept(next.item);
            lastReturned = next;
            next = next.next;
            nextIndex++;
        }
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

链表这个,依然要注意不用在foreach语法糖里使用remove这些。要循环删除,就要用迭代器删除:

LinkedList<Integer> linkedList = new LinkedList<>();
Iterator<Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    iterator.remove();
}

7、总结

(1)使用LinkedList遍历的是,如果使用for+index的方式来实现遍历,那么效率会很低,建议要使用迭代器的方式。
(2)和ArrayList比起来,插入、删除头结点,LinkedList确实快。
(3)因为需要遍历,所以在中间位置插入、删除节点,效率比起ArrayList的慢,其实ArrayList搬运走的是System.arraycopy方法,这个是native修饰的,表示这是个本地方法,这些基本都有用C来实现的方法,直接访问操作系统底层,效率很高。
(4)尾部插入、删除,还是ArrayList略快一些。因为ArrayList纯插入数据到数组就行,但 LinkedList 中多了 new 对象以及变换指针指向对象的过程,所以效率要低于 ArrayList。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章