從源碼分析java集合【LinkedList】

來源:互聯網
上載者:User

標籤:java編程   java集合源碼解析   

LinkedList是一個雙端鏈表,他繼承了AbstractSequentaiList順序列表,實現了List,Deque,Cloneable,和Serializable介面。Deque是雙端隊列的介面,LinkedList有記錄頭的 first 和 尾的 last,所以我們可以對隊列的兩端進行操作。它還實現了Cloneable和Serializeble介面,它們分別是實現隊列進行拷貝和序列化的介面。

LinkedList的節點的結構是:

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;        }    }
其中lLinkedList除了含有first和last兩個基本屬性外,還有:

transient int size = 0;//記錄集合中元素數量//Fields inherited from class java.util.AbstractListprotected transient int modCount = 0;//修了幾個的次數//當利用Iterator進行操作時會用上

它記錄了下一個節點和後一個節點。LinkedList的很多操作是調用以下函數來完成的:

/*    * 將一個元素作為頭結點插入集合中    * */    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++;    }    /*    * 將一個元素作為隊尾插入集合中    * */    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++;}    /**     *將一個元素插入在指定結點之前,其中指定結點不能為null     */    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++;    }    /**     * 刪除指定結點值,指定結點後的結點將作為頭結點,f不能為null     */    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;    }    /**     * 刪除指定結點值,指定結點前的結點將作為尾結點,f不能為null     */    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;    }    /**     * 刪除指定結點 ,x值不能為null     */    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;    }

需要注意的是LinkedList沒法在O(n)的時間複雜度內,根據index值來指定位置的節點進行操作,我們先來看看隨機訪問,修改,增加,修改的源碼:

public E get(int index) {        checkElementIndex(index);        return node(index).item;    } public E set(int index, E element) {        checkElementIndex(index);        Node<E> x = node(index);        E oldVal = x.item;        x.item = element;        return oldVal;    }public void add(int index, E element) {        checkPositionIndex(index);        if (index == size)            linkLast(element);        else            linkBefore(element, node(index));    }public E remove(int index) {        checkElementIndex(index);        return unlink(node(index));    }
checkXXXXIndex(index)函數是用來檢測index是否能用的,我們可以看到每次調用方法時,它都是在底層調用了node()方法,那它又是怎樣的呢

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;        }    }
首先會先確定index離對頭還是隊尾更近,在確定從哪開始遍曆。所以,LinkedList的隨機訪問效率為O(n)。因此我們不會通過調用

while(index < list.size()){    get(index++);}
來遍曆LinkedList,當需要遍曆LinkedList時怎麼辦呢,需要調用listIterator();或者descendingIterator();或者調用繼承自Deque的iterator();

無論是listIterator()還是descendingIterator()都是對LinkedList的內部類ListItr進行操作,它實現了ListIterator<E>.

private class ListItr implements ListIterator<E> {        private Node<E> lastReturned; <span style="white-space:pre"></span>//最後一次返回的節點        private Node<E> next;<span style="white-space:pre"></span>//下一個操作的節點        private int nextIndex;<span style="white-space:pre"></span>//next的索引        private int expectedModCount = modCount; <span style="white-space:pre"></span>//iterator的修改次數 當modCount != expectedModCount時會拋出ConcurrentModficationException        //方法        ......}

我們可以看到,它記錄了指向最後一次返回的節點資訊和下一次動作節點的資訊,所以我們對LinkedList遍曆時使用如下代碼:

ListIterator<String> iterator = list.listIterator();        while (iterator.hasNext()){            iterator.next()}
因為實現了ListIterator介面,所以它相對Iterator而言,還能夠add,set,previous,hasPrevious和previousIndex。還有一點需要提醒一下,ListItr有個屬性expectedModCount屬性是被賦值為LinkedList的modCount的,並且,調用ListItr的方法時,除了hasXXX或者XXXindex方法外,都會檢測expectedModCount 是否等於 modCount, 不等會被拋出異常,所以在調用LInkedList的XXXXIterator()方法後,都不應該在直接通過LinkedList的方法對List進行操作而應該直接利用XXXXIterator的方法進行操作。


從源碼分析java集合【LinkedList】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.