LinkedList源码解析

一、概念

LinkedList继承自AbstractSequentialList,实现List接口,获得简单的增删改查功能,实现Deque,获得双向队列的一些功能,实现Cloneable接口,获得克隆功能,实现

Serializable接口,实现序列化功能,LinkedList的操作非同步,所以均不是线程安全的。

二、详细分析

1、AbstractSequentialList

AbstractSequentialList继承自AbstractList,相当于List接口的简化版,AbstractSequentialList只支持按次序进行访问,不像AbstractList可以随机访问,如果想按照次序进行访问,只需要继承AbstractSequentialList这个类,实现一些指定的方法。

2、Deque

Deque继承Quene,实现一些基本的对双向队列操作的基本方法。

3、LinkedList

  • 属性
    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;
  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;
}
}

 三个属性均是transient修饰,意味着这三个属性不参与对象的序列化。

int size:初始容量为0;

Node<E> first :指向头结点;

 Node<E> first :指向尾结点;

Node<E>为静态内部类,记录当前结点,下一个结点,上一个结点

  •   构造方法
     /**
         * 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.
         *
         * @param  c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         */
        public LinkedList(Collection<? extends E> c) {
            this();
            addAll(c);
        }
    

      上面一个是无参构造,下面一个是带Collection参数的构造方法,执行此构造方法的时候,调用addAll()方法,实现集合的初始化。两个构造方法均没有对集合的size做限制,不用担心容量不足的问题。

  • 其他的均为增删改查的一些基本操作。

三、总结

  • LinkedList是一个以双向链表实现的List。
  • LinkedList还是一个双端队列,具有队列、双端队列、栈的特性。
  • LinkedList是线程不安全的。
  • LinkedList在头尾部添加元素,删除元素效率较高。
原文地址:https://www.cnblogs.com/wuhao-0206/p/13063832.html