1. 程式人生 > >【Java集合類】LinkedList原始碼分析(jdk1.8)

【Java集合類】LinkedList原始碼分析(jdk1.8)

ArrayListLinkedListList介面的兩種實現,具有相同的查詢、插入、刪除操作,只是底層的實現方式不一樣。LinkedList是以雙向連結串列形式實現的集合類。

其增刪操作由於不需要移動底層陣列資料,只需要修改連結串列節點指標,所以效率較高。但是隨機訪問時的定位操作效率較低,需要遍歷連結串列節點。(ArrayList與之相反)

資料結構

底層基於雙向連結串列實現的。並且元素允許 null 的存在。

其原始碼如下:

//沒有空頭節點的雙向連結串列
    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;

    /**
     * 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;

初始化

由於連結串列,初始化時不需要指定表的長度。

/**
     * 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);
    }

擴容

由於連結串列,擴容時只需要新建節點。

查詢操作

1、通過索引查詢元素(隨機訪問):

注意node(int index)函式:通過索引找到對應的節點。(後面很多方法都會用的)

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
/**
     * Returns the (non-null) Node at the specified element index.
     */
    //時間複雜度為n/2
    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;
        }
    }

2、直接查詢元素:

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

    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

插入操作

在介紹插入操作前,首先介紹根據插入連結串列位置的不同,幾種基本的插入連結串列方式:

  • (1)元素作為頭節點插入連結串列:
/**
     * Links e as first element.
     */
    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++;
    }

	public void addFirst(E e) {
        linkFirst(e);
    }
  • (2)元素作為尾節點插入連結串列:
/**
     * Links e as last element.
     */
    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 addLast(E e) {
        linkLast(e);
    }
  • (3)元素作為節點e的前驅節點插入連結串列(相當於元素作為連結串列的中間節點):
  /**
         * Inserts element e before non-null Node succ.
         */
        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++;
        }

1、插入單個元素

public boolean add(E e) {
        linkLast(e);
        return true;
    }

public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            //在node(index)節點之前插入
            linkBefore(element, node(index));
    }

2、插入集合:

	public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    
	//插入成第index個節點(= 即index節點後移 = 即在index節點之前插入)(index從0開始)
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
        //開始遍歷之前的前驅節點,最終的後繼節點
        Node<E> pred, succ;
        //特殊情況:當索引index=size時,通過node(index)找不到節點,超過範圍
        //(那為什麼不把索引設定為index-1,即插入到index-1節點後?那插入到0節點之前也是特殊情況)
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            //找到第index個節點
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            //後繼待定,指向下個遍歷的節點
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                //新節點左邊的所有連結成功
                pred.next = newNode;
            pred = newNode;
        }
        //連線最後一個節點pred右邊的所有連結
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

刪除操作

首先介紹根據刪除節點在連結串列位置的不同,幾種基本的刪除節點方式:

  • (1)刪除頭節點:
/**
     * 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;
    }

	public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
  • (2)刪除尾節點:
/**
     * 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;
    }

	public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
  • (3)刪除中間節點:
/**
     * 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;
    }

1、通過索引刪除元素:

	 public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

2、刪除指定元素:

	public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

佇列操作

主要操作:

	//取佇列頭節點,但不刪除
	//若first為空時,不丟擲錯誤
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    //若first為空時,丟擲錯誤
    public E element() {
        return getFirst();
    }

    //出佇列(頭刪)
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

	//入佇列(尾插)
    public boolean offer(E e) {
        return add(e);
    }

棧操作

主要操作:

	//入棧,頭插
    public void push(E e) {
        addFirst(e);
    }

    //出棧,頭刪
    public E pop() {
        return removeFirst();
    }

轉化成陣列

 	public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

@SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            //為什麼用到反射?泛型類在執行時無法new例項化,只能在執行時得到class物件
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }