LinkedList源碼解析——JDK1.8

1、LinkedList介紹

LinkedList 是一個繼承于AbstractSequentialList的雙向鏈表。它也可以被當作堆棧隊列雙端隊列進行操作。

LinkedList 實現 List 接口,能對它進行隊列操作。

LinkedList 實現 Deque 接口,即能將LinkedList當作雙端隊列使用。

LinkedList 實現了Cloneable接口,即覆蓋了函數clone(),能克隆。

LinkedList 實現java.io.Serializable接口,這意味著LinkedList支持序列化,能通過序列化去傳輸。

LinkedList 是非同步的。

2、關鍵點

  • LinkedList的本質是雙向鏈表

  • LinkedList繼承于AbstractSequentialList,并且實現了Dequeue接口。

  • LinkedList包含三個重要的成員:firstlastsize

    • first指向鏈表的第一個節點。
    • last 指向鏈表的最后一個節點。
    • size 是雙向鏈表中節點的個數。

3、節點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;
        }
    }

4、構造函數

    //構造一個空鏈表
    public LinkedList() {
    }

    //構建一個包含指定集合c的列表
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

5、add添加元素

LinkedList提供了頭插addFirst(E e)、尾插addLast(E e)、add(E e)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)、add(int index, E element)這些添加元素的方法。

    //頭插,在列表首部插入節點值e
    public void addFirst(E e) {
        linkFirst(e);
    }


    //頭插,也就是將節點值為e的節點設置為鏈表首節點
    private void linkFirst(E e) {
        final Node<E> f = first;
        //構建一個prev值為null,節點值為e,next值為f的新節點newNode
        final Node<E> newNode = new Node<>(null, e, f); 
        //將newNode作為首節點
        first = newNode;
        //如果原首節點為null,即原鏈表為null,則鏈表尾節點也設置為newNode
        if (f == null)
            last = newNode; 
        else 
            //否則,原首節點的prev設置為newNode
            f.prev = newNode;
        size++;  
        modCount++;
    }


    //尾插,在列表尾部插入節點值e,該方法等價于add()
    public void addLast(E e) {
        linkLast(e);
    }


    //尾插,在列表尾部插入節點值e
    public boolean add(E e) {
        linkLast(e);
        return true;
    }    


    //尾插,即將節點值為e的節點設置為鏈表的尾節點
    void linkLast(E e) {
        final Node<E> l = last;
        //構建一個prev值為l,節點值為e,next值為null的新節點newNode
        final Node<E> newNode = new Node<>(l, e, null);
        //將newNode作為尾節點
        last = newNode;
        //如果原尾節點為null,即原鏈表為null,則鏈表首節點也設置為newNode
        if (l == null)
            first = newNode; 
        else  
            //否則,原尾節點的next設置為newNode
            l.next = newNode;
        size++;
        modCount++;
    }


    //中間插入,在非空節點succ之前插入節點值e
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        //構建一個prev值為succ.prev,節點值為e,next值為succ的新節點newNode
        final Node<E> newNode = new Node<>(pred, e, succ);
        //設置newNode為succ的前節點
        succ.prev = newNode;
        //如果succ.prev為null,即如果succ為首節點,則將newNode設置為首節點
        if (pred == null)  
            first = newNode;
        else //如果succ不是首節點
            pred.next = newNode;
        size++;
        modCount++;
    }


    /**
     * 按照指定collection的迭代器所返回的元素順序,將該Collection中的所有元素添加到此鏈表的尾部
     * 如果指定的集合添加到鏈表的尾部的過程中,集合被修改,則該插入過程的后果是不確定的。
     * 一般這種情況發生在指定的集合為該鏈表的一部分,且其非空。
     * @throws NullPointerException 指定集合為null
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }



    //從指定的位置開始,將指定Collection中的所有元素插入到此鏈表中,
    //新元素的順序為指定Collection的迭代器所返回的元素順序。
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index); //index >= 0 && index <= size

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0) 
            return false;

        //succ指向當前需要插入節點的位置,pred指向其前一個節點
        Node<E> pred, succ; 
        if (index == size) { 
            //說明在列表尾部插入集合元素
            succ = null;
            pred = last;
        } else {
            //得到索引index所對應的節點
            succ = node(index); 
            pred = succ.prev;
        }

        //指定collection中的所有元素依次插入到此鏈表中指定位置的過程
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            //將元素值e,前繼節點pred“封裝”為一個新節點newNode
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)  //如果原鏈表為null,則新插入的節點作為鏈表首節點
                first = newNode; 
            else
                pred.next = newNode;
            pred = newNode;  //pred指針向后移動,指向下一個需插入節點位置的前一個節點
        }

        //集合元素插入完成后,與原鏈表index位置后面的子鏈表鏈接起來
        if (succ == null) { //說明之前是在列表尾部插入的集合元素
            last = pred;  //pred指向的是最后插入的那個節點
        } else { 
            pred.next = succ;
            succ.prev = pred;
        }

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



    //將指定的元素(E element)插入到列表的指定位置(index)
    public void add(int index, E element) {
        checkPositionIndex(index); //index >= 0 && index <= size

        if (index == size) 
            linkLast(element); //尾插入
        else
            linkBefore(element, node(index));  //中間插入
    }

6、remove刪除元素

    //移除首節點,并返回該節點的元素值
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }



    //刪除非空的首節點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; //將原首節點的next節點設置為首節點
        if (next == null)  //如果原鏈表只有一個節點,即原首節點,刪除后,鏈表為null
            last = null;
        else  
            next.prev = null;
        size--;
        modCount++;
        return element;
    }



    //移除尾節點,并返回該節點的元素值
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }



    //刪除非空的尾節點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; //將原尾節點的prev節點設置為尾節點
        if (prev == null) //如果原鏈表只有一個節點,則刪除后,鏈表為null
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }



    //移除此列表中指定位置上的元素
    public E remove(int index) {
        checkElementIndex(index);  //index >= 0 && index < size
        return unlink(node(index));
    }



    //刪除非空節點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; // help GC
        size--;
        modCount++;
        return element;
    }



    //移除列表中首次出現的指定元素(如果存在),LinkedList中允許存放重復的元素
    public boolean remove(Object o) {
        //由于LinkedList中允許存放null,因此下面通過兩種情況來分別處理
        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;
    }



    //清除列表中所有節點
    public void clear() {
        、、將所有的引用置null,讓GC回收對象
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

7、set修改元素

    //替換指定索引位置節點的元素值,并返回舊值
    public E set(int index, E element) {
        checkElementIndex(index); //index >= 0 && index < size
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

8、get查找元素

LinkedList提供了getFirst()、getLast()、contains(Object o)、get(int index)、indexOf(Object o)、lastIndexOf(Object o)這些查找元素的方法。

    //返回列表首節點元素值
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)  //如果首節點為null
            throw new NoSuchElementException();
        return f.item;
    }



    //返回列表尾節點元素值
    public E getLast() {
        final Node<E> l = last;
        if (l == null) //如果尾節點為null
            throw new NoSuchElementException();
        return l.item;
    }



    //判斷列表中是否包含有元素值o,
    //返回true當列表中至少存在一個元素值e,使得(o==null?e==null:o.equals(e))
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }



    //返回指定索引處的元素值
    public E get(int index) {
        checkElementIndex(index); //index >= 0 && index < size
        return node(index).item;  //node(index)返回指定索引位置index處的節點
    }



    //返回指定索引位置的節點
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //折半思想,當index < size/2時,從列表首節點向后查找
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {  //當index >= size/2時,從列表尾節點向前查找
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }



    //正向查找,返回LinkedList中元素值Object o第一次出現的位置,如果元素不存在,則返回-1
    public int indexOf(Object o) {
        int index = 0;
        //由于LinkedList中允許存放null,因此下面通過兩種情況來分別處理
        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;
    }



    //逆向查找,返回LinkedList中元素值Object o最后一次出現的位置,如果元素不存在,則返回-1
    public int lastIndexOf(Object o) {
        int index = size;
        //由于LinkedList中允許存放null,因此下面通過兩種情況來分別處理
        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;
    }

9、clone克隆

    //返回此 LinkedList實例的淺拷貝
    public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容