天天看點

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的類圖關系:

LinkedList實作原理

2、LinkedList資料結構原理

LinkedList底層的資料結構是基于雙向循環連結清單的,且頭結點中不存放資料,如下:

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類的代碼。

1 private static class Entry<E> {
 2    E element;
 3     Entry<E> next;
 4     Entry<E> previous;
 5 
 6     Entry(E element, Entry<E> next, Entry<E> previous) {
 7         this.element = element;
 8         this.next = next;
 9         this.previous = previous;
10    }
11 }      

節點類很簡單,element存放業務資料,previous與next分别存放前後節點的資訊(在資料結構中我們通常稱之為前後節點的指針)。

    LinkedList的構造方法:

1 public LinkedList() {
2     header.next = header.previous = header;
3 }
4 public LinkedList(Collection<? extends E> c) {
5     this();
6    addAll(c);
7 }      

4、構造方法

LinkedList提供了兩個構造方法。

第一個構造方法不接受參數,将header執行個體的previous和next全部指向header執行個體(注意,這個是一個雙向循環連結清單,如果不是循環連結清單,空連結清單的情況應該是header節點的前一節點和後一節點均為null),這樣整個連結清單其實就隻有header一個節點,用于表示一個空的連結清單。

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

LinkedList實作原理

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

 5、元素添加

1 public boolean addAll(Collection<? extends E> c) {
 2     return addAll(size, c);
 3 }
 4 // index參數指定collection中插入的第一個元素的位置
  5 public boolean addAll(int index, Collection<? extends E> c) {
 6     // 插入位置超過了連結清單的長度或小于0,報IndexOutOfBoundsException異常
  7     if (index < 0 || index > size)
 8         throw new IndexOutOfBoundsException("Index: "+index+
  9                                                 ", Size: "+size);
10     Object[] a = c.toArray();
11    int numNew = a.length;
12    // 若需要插入的節點個數為0則傳回false,表示沒有插入元素
13     if (numNew==0)
14         return false;
15     modCount++;//否則,插入對象,連結清單修改次數加1
16     // 儲存index處的節點。插入位置如果是size,則在頭結點前面插入,否則在擷取index處的節點插入
17     Entry<E> successor = (index==size ? header : entry(index));
18     // 擷取前一個節點,插入時需要修改這個節點的next引用
19     Entry<E> predecessor = successor.previous;
20     // 按順序将a數組中的第一個元素插入到index處,将之後的元素插在這個元素後面
21     for (int i=0; i<numNew; i++) {
22         // 結合Entry的構造方法,這條語句是插入操作,相當于C語言中連結清單中插入節點并修改指針
23         Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
24         // 插入節點後将前一節點的next指向目前節點,相當于修改前一節點的next指針
25         predecessor.next = e;
26         // 相當于C語言中成功插入元素後将指針向後移動一個位置以實作循環的功能
27         predecessor = e;
28   }
29     // 插入元素前index處的元素連結到插入的Collection的最後一個節點
30     successor.previous = predecessor;
31     // 修改size
32     size += numNew;
33     return true;
34 }      

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

1 private Entry<E> entry(int index) {
 2         if (index < 0 || index >= size)
 3             throw new IndexOutOfBoundsException("Index: "+index+
 4                                                 ", Size: "+size);
 5         Entry<E> e = header;
 6         // 根據這個判斷決定從哪個方向周遊這個連結清單
 7         if (index < (size >> 1)) {
 8             for (int i = 0; i <= index; i++)
 9                 e = e.next;
10         } else {
11             // 可以通過header節點向前周遊,說明這個一個循環雙向連結清單,header的previous指向連結清單的最後一個節點,這也驗證了構造方法中對于header節點的前後節點均指向自己的解釋
12             for (int i = size; i > index; i--)
13                 e = e.previous;
14        }
15         return e;
16     }      

下面說明雙向連結清單添加元素的原理:

添加資料: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執行個體的情況:

LinkedList實作原理

第二步:初始化一個預添加的Entry執行個體(newEntry)。

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

LinkedList實作原理

第三步:調整新加入節點和頭結點(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實作原理

下面分解“添加第二個資料”的步驟:

第一步:建立節點。

圖——添加第二個節點

LinkedList實作原理

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

圖——調整前後指針資訊

LinkedList實作原理

添加後續資料情況和上述一緻,LinkedList執行個體是沒有容量限制的。

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

LinkedList實作原理
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()

1 public void clear() {
 2     Entry<E> e = header.next;
 3     // e可以了解為一個移動的“指針”,因為是循環連結清單,是以回到header的時候說明已經沒有節點了
 4      while (e != header) {
 5        // 保留e的下一個節點的引用
 6         Entry<E> next = e.next;
 7         // 解除節點e對前後節點的引用
 8         e.next = e.previous = null;
 9         // 将節點e的内容置空
10         e.element = null;
11         // 将e移動到下一個節點
12         e = next;
13  }
14     // 将header構造成一個循環連結清單,同構造方法構造一個空的LinkedList
15     header.next = header.previous = header;
16     // 修改size
17     size = 0;
18     modCount++;
19 }      

   資料包含 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)方法。

1 private E remove(Entry<E> e) {
 2     if (e == header)
 3         throw new NoSuchElementException();
 4     // 保留将被移除的節點e的内容
 5     E result = e.element;
 6    // 将前一節點的next引用指派為e的下一節點
 7     e.previous.next = e.next;
 8    // 将e的下一節點的previous指派為e的上一節點
 9     e.next.previous = e.previous;
10    // 上面兩條語句的執行已經導緻了無法在連結清單中通路到e節點,而下面解除了e節點對前後節點的引用
11    e.next = e.previous = null;
12   // 将被移除的節點的内容設為null
13   e.element = null;
14   // 修改size大小
15   size--;
16   modCount++;
17   // 傳回移除節點e的内容
18   return result;
19 }      

由于删除了某一節點是以調整相應節點的前後指針資訊,如下:

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()

1 public Object clone() {
 2     LinkedList<E> clone = null;
 3     try {
 4         clone = (LinkedList<E>) super.clone();
 5     } catch (CloneNotSupportedException e) {
 6         throw new InternalError();
 7    }
 8     clone.header = new Entry<E>(null, null, null);
 9     clone.header.next = clone.header.previous = clone.header;
10     clone.size = 0;
11     clone.modCount = 0;
12     for (Entry<E> e = header.next; e != header; e = e.next)
13        clone.add(e.element);
14     return clone;
15 }      

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

    toArray()

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

建立大小和LinkedList相等的數組result,周遊連結清單,将每個節點的元素element複制到數組中,傳回數組。

    toArray(T[] a)

1 public <T> T[] toArray(T[] a) {
 2     if (a.length < size)
 3         a = (T[])java.lang.reflect.Array.newInstance(
 4                                a.getClass().getComponentType(), size);
 5     int i = 0;
 6     Object[] result = a;
 7     for (Entry<E> e = header.next; e != header; e = e.next)
 8         result[i++] = e.element;
 9     if (a.length > size)
10         a[size] = null;
11     return a;
12 }      

先判斷出入的數組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。

1 private class ListItr implements ListIterator<E> {
  2 // 最近一次傳回的節點,也是目前持有的節點
  3     private Entry<E> lastReturned = header;
  4     // 對下一個元素的引用
  5     private Entry<E> next;
  6     // 下一個節點的index
  7     private int nextIndex;
  8     private int expectedModCount = modCount;
  9     // 構造方法,接收一個index參數,傳回一個ListItr對象
 10     ListItr(int index) {
 11         // 如果index小于0或大于size,抛出IndexOutOfBoundsException異常
 12         if (index < 0 || index > size)
 13         throw new IndexOutOfBoundsException("Index: "+index+
 14                             ", Size: "+size);
 15         // 判斷周遊方向
 16         if (index < (size >> 1)) {
 17         // next指派為第一個節點
 18         next = header.next;
 19         // 擷取指定位置的節點
 20         for (nextIndex=0; nextIndex<index; nextIndex++)
 21             next = next.next;
 22         } else {
 23 // else中的處理和if塊中的處理一緻,隻是周遊方向不同
 24         next = header;
 25         for (nextIndex=size; nextIndex>index; nextIndex--)
 26             next = next.previous;
 27        }
 28    }
 29     // 根據nextIndex是否等于size判斷時候還有下一個節點(也可以了解為是否周遊完了LinkedList)
 30     public boolean hasNext() {
 31         return nextIndex != size;
 32    }
 33     // 擷取下一個元素
 34     public E next() {
 35        checkForComodification();
 36         // 如果nextIndex==size,則已經周遊完連結清單,即沒有下一個節點了(實際上是有的,因為是循環連結清單,任何一個節點都會有上一個和下一個節點,這裡的沒有下一個節點隻是說所有節點都已經周遊完了)
 37         if (nextIndex == size)
 38         throw new NoSuchElementException();
 39         // 設定最近一次傳回的節點為next節點
 40         lastReturned = next;
 41         // 将next“向後移動一位”
 42         next = next.next;
 43         // index計數加1
 44         nextIndex++;
 45         // 傳回lastReturned的元素
 46         return lastReturned.element;
 47    }
 48 
 49     public boolean hasPrevious() {
 50         return nextIndex != 0;
 51    }
 52     // 傳回上一個節點,和next()方法相似
 53     public E previous() {
 54         if (nextIndex == 0)
 55         throw new NoSuchElementException();
 56 
 57         lastReturned = next = next.previous;
 58         nextIndex--;
 59        checkForComodification();
 60         return lastReturned.element;
 61    }
 62 
 63     public int nextIndex() {
 64         return nextIndex;
 65    }
 66 
 67     public int previousIndex() {
 68         return nextIndex-1;
 69    }
 70     // 移除目前Iterator持有的節點
 71     public void remove() {
 72            checkForComodification();
 73             Entry<E> lastNext = lastReturned.next;
 74             try {
 75                 LinkedList.this.remove(lastReturned);
 76             } catch (NoSuchElementException e) {
 77                 throw new IllegalStateException();
 78            }
 79         if (next==lastReturned)
 80                 next = lastNext;
 81             else
 82         nextIndex--;
 83         lastReturned = header;
 84         expectedModCount++;
 85    }
 86     // 修改目前節點的内容
 87     public void set(E e) {
 88         if (lastReturned == header)
 89         throw new IllegalStateException();
 90        checkForComodification();
 91         lastReturned.element = e;
 92    }
 93     // 在目前持有節點後面插入新節點
 94     public void add(E e) {
 95        checkForComodification();
 96         // 将最近一次傳回節點修改為header
 97         lastReturned = header;
 98        addBefore(e, next);
 99         nextIndex++;
100         expectedModCount++;
101    }
102     // 判斷expectedModCount和modCount是否一緻,以確定通過ListItr的修改操作正确的反映在LinkedList中
103     final void checkForComodification() {
104         if (modCount != expectedModCount)
105         throw new ConcurrentModificationException();
106    }
107 }      

下面是一個ListItr的使用執行個體。

1 LinkedList<String> list = new LinkedList<String>();
 2         list.add("First");
 3         list.add("Second");
 4         list.add("Thrid");
 5        System.out.println(list);
 6         ListIterator<String> itr = list.listIterator();
 7         while (itr.hasNext()) {
 8            System.out.println(itr.next());
 9        }
10         try {
11             System.out.println(itr.next());// throw Exception
12         } catch (Exception e) {
13             // TODO: handle exception
14        }
15         itr = list.listIterator();
16        System.out.println(list);
17        System.out.println(itr.next());
18         itr.add("new node1");
19        System.out.println(list);
20         itr.add("new node2");
21        System.out.println(list);
22        System.out.println(itr.next());
23         itr.set("modify node");
24        System.out.println(list);
25        itr.remove();
26         System.out.println(list);      
1 結果:
 2 [First, Second, Thrid]
 3 First
 4 Second
 5 Thrid
 6 [First, Second, Thrid]
 7 First
 8 [First, new node1, Second, Thrid]
 9 [First, new node1, new node2, Second, Thrid]
10 Second
11 [First, new node1, new node2, modify node, Thrid]
12 [First, new node1, new node2, Thrid]      

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

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

下面分析詳細分析DescendingIterator類。

1 private class DescendingIterator implements Iterator {
 2    // 擷取ListItr對象
 3 final ListItr itr = new ListItr(size());
 4 // hasNext其實是調用了itr的hasPrevious方法
 5    public boolean hasNext() {
 6        return itr.hasPrevious();
 7    }
 8 // next()其實是調用了itr的previous方法
 9    public E next() {
10        return itr.previous();
11    }
12    public void remove() {
13        itr.remove();
14    }
15 }      

從類名和上面的代碼可以看出這是一個反向的Iterator,代碼很簡單,都是調用的ListItr類中的方法。

http://www.cnblogs.com/deepbreath/p/5235419.html 

http://blog.csdn.net/zheng0518/article/details/42198599

關于ArrayList與LinkedList的比較分析

        a,ArrayList底層采用數組實作,LinkedList底層采用雙向連結清單實作

        b,當執行插入或者删除操作時,采用LinkedList比較好

        c,當執行搜尋操作時,使用ArrayList比較好

        d,當向ArrayList添加一個對象(實際上是對象的引用),就是将對象放入了底層維護的數組中。當向LinkedList添加對象,實際上則是内部生成一個Entry對象。

http://blog.csdn.net/huang211630/article/details/45645641

繼續閱讀