LinkedList源碼解析



一、源碼解析

    1、 LinkedList類定義。

 

 

public class LinkedList<E>
     extends AbstractSequentialList<E>
     implements List<E>, Deque<E>, Cloneable, java.io.Serializable

LinkedList 是一個繼承於AbstractSequentialList的雙向鏈表。它也可以被當作堆棧、隊列或雙端隊列進行操作。
LinkedList 實現 List 接口,能對它進行隊列操作。
LinkedList 實現 Deque 接口,即能將LinkedList當作雙端隊列使用。
LinkedList 實現了Cloneable接口,即覆蓋了函數clone(),能克隆。
LinkedList 實現java.io.Serializable接口,這意味着LinkedList支持序列化,能通過序列化去傳輸。
LinkedList 是非同步的。

 

爲什麼要繼承自AbstractSequentialList ?

AbstractSequentialList 實現了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)這些骨幹性函數。降低了List接口的複雜度。這些接口都是隨機訪問List的,LinkedList是雙向鏈表;既然它繼承於AbstractSequentialList,就相當於已經實現了“get(int index)這些接口”。

此外,我們若需要通過AbstractSequentialList自己實現一個列表,只需要擴展此類,並提供 listIterator() 和 size() 方法的實現即可。若要實現不可修改的列表,則需要實現列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。

 

LinkedList的類圖關係:

 

2、LinkedList數據結構原理

 

LinkedList底層的數據結構是基於雙向循環鏈表的,且頭結點中不存放數據,如下:

 

既然是雙向鏈表,那麼必定存在一種數據結構——我們可以稱之爲節點,節點實例保存業務數據,前一個節點的位置信息和後一個節點位置信息,如下圖所示:

   3、私有屬性

 LinkedList中之定義了兩個屬性:

 

 

1 private transient Entry<E> header = new Entry<E>(null, null, null);
2 private transient int size = 0;

 

header是雙向鏈表的頭節點,它是雙向鏈表節點所對應的類Entry的實例。Entry中包含成員變量: previous, next, element。其中,previous是該節點的上一個節點,next是該節點的下一個節點,element是該節點所包含的值。 
  size是雙向鏈表中節點實例的個數。

首先來了解節點類Entry類的代碼。

 

private static class Entry<E> {
   E element;
    Entry<E> next;
    Entry<E> previous;

    Entry(E element, Entry<E> next, Entry<E> previous) {
        this.element = element;
        this.next = next;
        this.previous = previous;
   }
}

 

節點類很簡單,element存放業務數據,previous與next分別存放前後節點的信息(在數據結構中我們通常稱之爲前後節點的指針)。

    LinkedList的構造方法:

 

public LinkedList() {
    header.next = header.previous = header;
}
public LinkedList(Collection<? extends E> c) {
    this();
   addAll(c);
}

 

4、構造方法

LinkedList提供了兩個構造方法。

第一個構造方法不接受參數,將header實例的previous和next全部指向header實例(注意,這個是一個雙向循環鏈表,如果不是循環鏈表,空鏈表的情況應該是header節點的前一節點和後一節點均爲null),這樣整個鏈表其實就只有header一個節點,用於表示一個空的鏈表。

 

執行完構造函數後,header實例自身形成一個閉環,如下圖所示:

 

第二個構造方法接收一個Collection參數c,調用第一個構造方法構造一個空的鏈表,之後通過addAll將c中的元素全部添加到鏈表中。

 

 5、元素添加

public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}
// index參數指定collection中插入的第一個元素的位置
public boolean addAll(int index, Collection<? extends E> c) {
    // 插入位置超過了鏈表的長度或小於0,報IndexOutOfBoundsException異常
    if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
    Object[] a = c.toArray();
   int numNew = a.length;
   // 若需要插入的節點個數爲0則返回false,表示沒有插入元素
    if (numNew==0)
        return false;
    modCount++;//否則,插入對象,鏈表修改次數加1
    // 保存index處的節點。插入位置如果是size,則在頭結點前面插入,否則在獲取index處的節點插入
    Entry<E> successor = (index==size ? header : entry(index));
    // 獲取前一個節點,插入時需要修改這個節點的next引用
    Entry<E> predecessor = successor.previous;
    // 按順序將a數組中的第一個元素插入到index處,將之後的元素插在這個元素後面
    for (int i=0; i<numNew; i++) {
        // 結合Entry的構造方法,這條語句是插入操作,相當於C語言中鏈表中插入節點並修改指針
        Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
        // 插入節點後將前一節點的next指向當前節點,相當於修改前一節點的next指針
        predecessor.next = e;
        // 相當於C語言中成功插入元素後將指針向後移動一個位置以實現循環的功能
        predecessor = e;
  }
    // 插入元素前index處的元素鏈接到插入的Collection的最後一個節點
    successor.previous = predecessor;
    // 修改size
    size += numNew;
    return true;
}

 

 

構造方法中的調用了addAll(Collection<? extends E> c)方法,而在addAll(Collection<? extends E> c)方法中僅僅是將size當做index參數調用了addAll(int index,Collection<? extends E> c)方法。

 

 

private Entry<E> entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;
        // 根據這個判斷決定從哪個方向遍歷這個鏈表
        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else {
            // 可以通過header節點向前遍歷,說明這個一個循環雙向鏈表,header的previous指向鏈表的最後一個節點,這也驗證了構造方法中對於header節點的前後節點均指向自己的解釋
            for (int i = size; i > index; i--)
                e = e.previous;
       }
        return e;
    }

 

 

下面說明雙向鏈表添加元素的原理:

添加數據:add()

// 將元素(E)添加到LinkedList中
     public boolean add(E e) {
         // 將節點(節點數據是e)添加到表頭(header)之前。
         // 即,將節點添加到雙向鏈表的末端。
         addBefore(e, header);
         return true;
     }

     public void add(int index, E element) {
         addBefore(element, (index==size ? header : entry(index)));
     }
    
    private Entry<E> addBefore(E e, Entry<E> entry) {
         Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
         newEntry.previous.next = newEntry;
         newEntry.next.previous = newEntry;
         size++;
         modCount++;
         return newEntry;
    }

 

addBefore(E e,Entry<E> entry)方法是個私有方法,所以無法在外部程序中調用(當然,這是一般情況,你可以通過反射上面的還是能調用到的)。

addBefore(E e,Entry<E> entry)先通過Entry的構造方法創建e的節點newEntry(包含了將其下一個節點設置爲entry,上一個節點設置爲entry.previous的操作,相當於修改newEntry的“指針”),之後修改插入位置後newEntry的前一節點的next引用和後一節點的previous引用,使鏈表節點間的引用關係保持正確。之後修改和size大小和記錄modCount,然後返回新插入的節點。

下面分解“添加第一個數據”的步驟:

第一步:初始化後LinkedList實例的情況:

第二步:初始化一個預添加的Entry實例(newEntry)。

Entry newEntry = newEntry(e, entry, entry.previous);

 

 

第三步:調整新加入節點和頭結點(header)的前後指針。

newEntry.previous.next = newEntry;

newEntry.previous即header,newEntry.previous.next即header的next指向newEntry實例。在上圖中應該是“4號線”指向newEntry。

newEntry.next.previous = newEntry;

newEntry.next即header,newEntry.next.previous即header的previous指向newEntry實例。在上圖中應該是“3號線”指向newEntry。

調整後如下圖所示:

圖——加入第一個節點後LinkedList示意圖

下面分解“添加第二個數據”的步驟:

第一步:新建節點。

圖——添加第二個節點

第二步:調整新節點和頭結點的前後指針信息。

圖——調整前後指針信息

添加後續數據情況和上述一致,LinkedList實例是沒有容量限制的。

 

總結,addBefore(E e,Entry<E> entry)實現在entry之前插入由e構造的新節點。而add(E e)實現在header節點之前插入由e構造的新節點。爲了便於理解,下面給出插入節點的示意圖。

public void addFirst(E e) {
     addBefore(e, header.next);
 }

 public void addLast(E e) {
     addBefore(e, header);
 }

 看上面的示意圖,結合addBefore(E e,Entry<E> entry)方法,很容易理解addFrist(E e)只需實現在header元素的下一個元素之前插入,即示意圖中的一號之前。addLast(E e)只需在實現在header節點前(因爲是循環鏈表,所以header的前一個節點就是鏈表的最後一個節點)插入節點(插入後在2號節點之後)。

 

    清除數據clear()

public void clear() {
    Entry<E> e = header.next;
    // e可以理解爲一個移動的“指針”,因爲是循環鏈表,所以回到header的時候說明已經沒有節點了
     while (e != header) {
       // 保留e的下一個節點的引用
        Entry<E> next = e.next;
        // 解除節點e對前後節點的引用
        e.next = e.previous = null;
        // 將節點e的內容置空
        e.element = null;
        // 將e移動到下一個節點
        e = next;
 }
    // 將header構造成一個循環鏈表,同構造方法構造一個空的LinkedList
    header.next = header.previous = header;
    // 修改size
    size = 0;
    modCount++;
}

 

   數據包含 contains(Object o)

public boolean contains(Object o) {
     return indexOf(o) != -1;
 }
 // 從前向後查找,返回“值爲對象(o)的節點對應的索引”  不存在就返回-1 
 public int indexOf(Object o) {
      int index = 0;
      if (o==null) {
          for (Entry e = header.next; e != header; e = e.next) {
              if (e.element==null)
                  return index;
              index++;
         }
      } else {
         for (Entry e = header.next; e != header; e = e.next) {
             if (o.equals(e.element))
                 return index;
             index++;
        }
    }
     return -1;
 }

indexOf(Object o)判斷o鏈表中是否存在節點的element和o相等,若相等則返回該節點在鏈表中的索引位置,若不存在則放回-1。

contains(Object o)方法通過判斷indexOf(Object o)方法返回的值是否是-1來判斷鏈表中是否包含對象o。

 

6、刪除數據remove()

幾個remove方法最終都是調用了一個私有方法:remove(Entry<E> e),只是其他簡單邏輯上的區別。下面分析remove(Entry<E> e)方法。

 

private E remove(Entry<E> e) {
    if (e == header)
        throw new NoSuchElementException();
    // 保留將被移除的節點e的內容
    E result = e.element;
   // 將前一節點的next引用賦值爲e的下一節點
    e.previous.next = e.next;
   // 將e的下一節點的previous賦值爲e的上一節點
    e.next.previous = e.previous;
   // 上面兩條語句的執行已經導致了無法在鏈表中訪問到e節點,而下面解除了e節點對前後節點的引用
   e.next = e.previous = null;
  // 將被移除的節點的內容設爲null
  e.element = null;
  // 修改size大小
  size--;
  modCount++;
  // 返回移除節點e的內容
  return result;
}

 

由於刪除了某一節點因此調整相應節點的前後指針信息,如下:

e.previous.next = e.next;//預刪除節點的前一節點的後指針指向預刪除節點的後一個節點。 

e.next.previous = e.previous;//預刪除節點的後一節點的前指針指向預刪除節點的前一個節點。 

清空預刪除節點:

e.next = e.previous = null;

e.element = null;

交給gc完成資源回收,刪除操作結束。

與ArrayList比較而言,LinkedList的刪除動作不需要“移動”很多數據,從而效率更高。

 

7、數據獲取get()

Get(int)方法的實現在remove(int)中已經涉及過了。首先判斷位置信息是否合法(大於等於0,小於當前LinkedList實例的Size),然後遍歷到具體位置,獲得節點的業務數據(element)並返回。

注意:爲了提高效率,需要根據獲取的位置判斷是從頭還是從尾開始遍歷。

// 獲取雙向鏈表中指定位置的節點    
    private Entry<E> entry(int index) {    
        if (index < 0 || index >= size)    
            throw new IndexOutOfBoundsException("Index: "+index+    
                                                ", Size: "+size);    
        Entry<E> e = header;    
        // 獲取index處的節點。    
        // 若index < 雙向鏈表長度的1/2,則從前先後查找;    
        // 否則,從後向前查找。    
        if (index < (size >> 1)) {    
            for (int i = 0; i <= index; i++)    
                e = e.next;    
        } else {    
            for (int i = size; i > index; i--)    
                e = e.previous;    
        }    
        return e;    
    }

注意細節:位運算與直接做除法的區別。先將index與長度size的一半比較,如果index<size/2,就只從位置0往後遍歷到位置index處,而如果index>size/2,就只從位置size往前遍歷到位置index處。這樣可以減少一部分不必要的遍歷

 

8、數據複製clone()與toArray()

clone()

public Object clone() {
    LinkedList<E> clone = null;
    try {
        clone = (LinkedList<E>) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new InternalError();
   }
    clone.header = new Entry<E>(null, null, null);
    clone.header.next = clone.header.previous = clone.header;
    clone.size = 0;
    clone.modCount = 0;
    for (Entry<E> e = header.next; e != header; e = e.next)
       clone.add(e.element);
    return clone;
}

 調用父類的clone()方法初始化對象鏈表clone,將clone構造成一個空的雙向循環鏈表,之後將header的下一個節點開始將逐個節點添加到clone中。最後返回克隆的clone對象。

    toArray()

public Object[] toArray() {
    Object[] result = new Object[size];
    int i = 0;
    for (Entry<E> e = header.next; e != header; e = e.next)
        result[i++] = e.element;
    return result;
}

創建大小和LinkedList相等的數組result,遍歷鏈表,將每個節點的元素element複製到數組中,返回數組。

    toArray(T[] a)

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                               a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Entry<E> e = header.next; e != header; e = e.next)
        result[i++] = e.element;
    if (a.length > size)
        a[size] = null;
    return a;
}

先判斷出入的數組a的大小是否足夠,若大小不夠則拓展。這裏用到了發射的方法,重新實例化了一個大小爲size的數組。之後將數組a賦值給數組result,遍歷鏈表向result中添加的元素。最後判斷數組a的長度是否大於size,若大於則將size位置的內容設置爲null。返回a。

    從代碼中可以看出,數組a的length小於等於size時,a中所有元素被覆蓋,被拓展來的空間存儲的內容都是null;若數組a的length的length大於size,則0至size-1位置的內容被覆蓋,size位置的元素被設置爲null,size之後的元素不變。

    爲什麼不直接對數組a進行操作,要將a賦值給result數組之後對result數組進行操作?

 

9、遍歷數據:Iterator()

    LinkedList的Iterator

    除了Entry,LinkedList還有一個內部類:ListItr。

    ListItr實現了ListIterator接口,可知它是一個迭代器,通過它可以遍歷修改LinkedList。

    在LinkedList中提供了獲取ListItr對象的方法:listIterator(int index)。

 

1 public ListIterator<E> listIterator(int index) {
2     return new ListItr(index);
3 }

 

該方法只是簡單的返回了一個ListItr對象。

    LinkedList中還有通過集成獲得的listIterator()方法,該方法只是調用了listIterator(int index)並且傳入0。

二、ListItr

    下面詳細分析ListItr。

 

private class ListItr implements ListIterator<E> {
// 最近一次返回的節點,也是當前持有的節點
    private Entry<E> lastReturned = header;
    // 對下一個元素的引用
    private Entry<E> next;
    // 下一個節點的index
    private int nextIndex;
    private int expectedModCount = modCount;
    // 構造方法,接收一個index參數,返回一個ListItr對象
    ListItr(int index) {
        // 如果index小於0或大於size,拋出IndexOutOfBoundsException異常
        if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: "+index+
                            ", Size: "+size);
        // 判斷遍歷方向
        if (index < (size >> 1)) {
        // next賦值爲第一個節點
        next = header.next;
        // 獲取指定位置的節點
        for (nextIndex=0; nextIndex<index; nextIndex++)
            next = next.next;
        } else {
// else中的處理和if塊中的處理一致,只是遍歷方向不同
        next = header;
        for (nextIndex=size; nextIndex>index; nextIndex--)
            next = next.previous;
       }
   }
    // 根據nextIndex是否等於size判斷時候還有下一個節點(也可以理解爲是否遍歷完了LinkedList)
    public boolean hasNext() {
        return nextIndex != size;
   }
    // 獲取下一個元素
    public E next() {
       checkForComodification();
        // 如果nextIndex==size,則已經遍歷完鏈表,即沒有下一個節點了(實際上是有的,因爲是循環鏈表,任何一個節點都會有上一個和下一個節點,這裏的沒有下一個節點只是說所有節點都已經遍歷完了)
        if (nextIndex == size)
        throw new NoSuchElementException();
        // 設置最近一次返回的節點爲next節點
        lastReturned = next;
        // 將next“向後移動一位”
        next = next.next;
        // index計數加1
        nextIndex++;
        // 返回lastReturned的元素
        return lastReturned.element;
   }

    public boolean hasPrevious() {
        return nextIndex != 0;
   }
    // 返回上一個節點,和next()方法相似
    public E previous() {
        if (nextIndex == 0)
        throw new NoSuchElementException();

        lastReturned = next = next.previous;
        nextIndex--;
       checkForComodification();
        return lastReturned.element;
   }

    public int nextIndex() {
        return nextIndex;
   }

    public int previousIndex() {
        return nextIndex-1;
   }
    // 移除當前Iterator持有的節點
    public void remove() {
           checkForComodification();
            Entry<E> lastNext = lastReturned.next;
            try {
                LinkedList.this.remove(lastReturned);
            } catch (NoSuchElementException e) {
                throw new IllegalStateException();
           }
        if (next==lastReturned)
                next = lastNext;
            else
        nextIndex--;
        lastReturned = header;
        expectedModCount++;
   }
    // 修改當前節點的內容
    public void set(E e) {
        if (lastReturned == header)
        throw new IllegalStateException();
       checkForComodification();
        lastReturned.element = e;
   }
    // 在當前持有節點後面插入新節點
    public void add(E e) {
       checkForComodification();
        // 將最近一次返回節點修改爲header
        lastReturned = header;
       addBefore(e, next);
        nextIndex++;
        expectedModCount++;
   }
    // 判斷expectedModCount和modCount是否一致,以確保通過ListItr的修改操作正確的反映在LinkedList中
    final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
   }
}

 

下面是一個ListItr的使用實例。

 

LinkedList<String> list = new LinkedList<String>();
        list.add("First");
        list.add("Second");
        list.add("Thrid");
       System.out.println(list);
        ListIterator<String> itr = list.listIterator();
        while (itr.hasNext()) {
           System.out.println(itr.next());
       }
        try {
            System.out.println(itr.next());// throw Exception
        } catch (Exception e) {
            // TODO: handle exception
       }
        itr = list.listIterator();
       System.out.println(list);
       System.out.println(itr.next());
        itr.add("new node1");
       System.out.println(list);
        itr.add("new node2");
       System.out.println(list);
       System.out.println(itr.next());
        itr.set("modify node");
       System.out.println(list);
       itr.remove();
        System.out.println(list);

結果:
[First, Second, Thrid]
First
Second
Thrid
[First, Second, Thrid]
First
[First, new node1, Second, Thrid]
[First, new node1, new node2, Second, Thrid]
Second
[First, new node1, new node2, modify node, Thrid]
[First, new node1, new node2, Thrid]

LinkedList還有一個提供Iterator的方法:descendingIterator()。該方法返回一個DescendingIterator對象。DescendingIterator是LinkedList的一個內部類。

 

1 public Iterator<E> descendingIterator() {
2    return new DescendingIterator();
3 }

 

下面分析詳細分析DescendingIterator類。

 

private class DescendingIterator implements Iterator {
   // 獲取ListItr對象
final ListItr itr = new ListItr(size());
// hasNext其實是調用了itr的hasPrevious方法
   public boolean hasNext() {
       return itr.hasPrevious();
   }
// next()其實是調用了itr的previous方法
   public E next() {
       return itr.previous();
   }
   public void remove() {
       itr.remove();
   }
}
從類名和上面的代碼可以看出這是一個反向的Iterator,代碼很簡單,都是調用的ListItr類中的方法。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章