JDK1.8源碼之LinkedList

LinkedList採用雙鏈表的數據結構,可以用作列表做存儲,也可以用做雙端隊列。
部分屬性與Node結構

	//指向列表的第一個元素
    transient Node<E> first;

	//指向列表的最後一個元素
    transient Node<E> last;
	//Node節點
    private static class Node<E> {
        E item;
        Node<E> next;//next指針
        Node<E> prev;//prev指針

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

add方法

    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)
            first = newNode;//l爲空,說明原來無節點,此新加入的節點既爲首節點,也爲尾節點
        else
            l.next = newNode;//新節點加在尾節點之後
        size++;
        modCount++;
    }

remove方法

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

get方法

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

與ArrayList對比

  • 存儲結構不同:ArrayList使用Object數組,LinkedList使用雙鏈表,存儲同樣的數據LinkedList比ArrayList更耗費空間;
  • 使用場景不同:ArrayList的隨機訪問效率高,但增加(擴容時元素需要進行復制)或者刪除(可能存在很多元素需要移動)的效率低;LinkedList隨機訪問效率低,增加和刪除操作快;對於少量數據或者大量但不經常增刪的數據,比較適合用ArrayList,對於大量且經常需要增刪的數據建議用LinkedList
  • 線程安全性:都不是線程安全的集合;
  • 實現的接口:都實現了Collection,List等接口,LinkedList還實現了Deque接口,可以用作雙端隊列;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章