常用集合之LinkedList源码浅析

上一篇 【ArrayList和Vector源码解刨对比

先看 LinkedList 部分源码:


public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    //链表大小
    transient int size = 0;
    //首节点
    transient Node<E> first;
    //尾节点
    transient Node<E> last;

    //添加一个元素 ,默认是添加到链表的尾部
    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)//如果尾节点为null,表示链表为空,首节点为第一个添加的节点
            first = newNode;
        else
            l.next = newNode; //和新添加的节点连接起来
        size++;
        modCount++;
    }
}

我们来看看NodeNodeLinkedList的内部类,源码如下,类似C++中的结构体:

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

由源码可见,每一个节点都是知道自己上一个节点或者说父亲节点(首节点除外),同时也知道自己的下一个节点或者说子节点(尾节点除外)。
所以,可知LinkedList实际上就是一个 双向链表 如下图:

由此,链表添加数据较ArrayList快,由上篇文章分析可知,ArrayList的添加数据最终是调用底层C++或是C的代码,这是一个耗时操作。而LinkedList采用特殊的数据结构链表的形式,插入就相对简单快速。相反,LinkedList查询效率就不敌ArrayList了。

猜你喜欢

转载自blog.csdn.net/She_lock/article/details/81777111