1. 程式人生 > >thinking in java (十二) ----- 集合之LinkedList

thinking in java (十二) ----- 集合之LinkedList

LinkedList介紹

  • LinkedList簡介

LinkedList是一個繼承與AbstractSequentialList的雙向連結串列,他也可以當做堆疊,佇列或者雙向佇列進行操作。

LinkedList實現了List介面,能進行佇列操作

LinkedList實現Deque介面,即能將LinkedList當做雙向佇列使用

LinkedList實現了Cloneable介面,

LinkedList實現Serializable介面,這意味著LinkedList支援序列化,能通過序列化去傳輸

LinkedList是非同步的,執行緒不安全

  • 建構函式
  public LinkedList() {
    }
預設建構函式,
————————————————————
public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
建立一個LinkedList,包含元素為collection的特定型別
  • AbstractSequentialList簡介

在介紹LinkedList之前,先介紹其父類AbstractSequentialList,AbstractSequentialList實現了List中的get,set,add,remove等函式,這些介面都是隨機訪問List的,LinkedList是雙向連結串列,繼承與AbstractSequentialList,也就實現了這些介面。

LinkedList資料結構

LinkedList的繼承關係

java.lang.Object
   ↳     java.util.AbstractCollection<E>
         ↳     java.util.AbstractList<E>
               ↳     java.util.AbstractSequentialList<E>
                     ↳     java.util.LinkedList<E>

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

LinkedList與collection關係如下圖:

LinkedList的本質是雙向列表:

1,LinkedList繼承與Abst...,並且實現了Deque介面,

2,LinkedList包含兩個重要的成員:size和header。header是雙向連結串列的表頭,他是雙向連結串列對應的類的Entry例項,Entry中包含成員變數,previous,next,element,分別是上一個節點,下一個節點,和本節點包含的資料。size是雙向連結串列中節點的個數

LinkedList原始碼解析

LinkedList大致說明:

LinkedList實際上是通過雙向連結串列實現的,既然是雙向連結串列,那麼其順序訪問會非常高效,但是隨機訪問非常低效

也實現了List介面,也就是說實現了get,remove等根據索引來獲取,刪除節點的函式。但是LinkedList是雙向連結串列,其是如何將雙向連結串列和索引值聯絡起來的呢

實際上是通過一個計數索引值實現的,比如我們呼叫get(index),首先會比較“index”和雙向連結串列長度的1/2。如果前者大,就從連結串列前面開始往後查詢,直到index位置,否則,就從後往前找。這就是將雙向連結串列和索引值聯絡起來的方法。

package java.util;

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    // 連結串列的表頭,表頭不包含任何資料。Entry是個連結串列類資料結構。
    private transient Entry<E> header = new Entry<E>(null, null, null);

    // LinkedList中元素個數
    private transient int size = 0;

    // 預設建構函式:建立一個空的連結串列
    public LinkedList() {
        header.next = header.previous = header;
    }

    // 包含“集合”的建構函式:建立一個包含“集合”的LinkedList
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    // 獲取LinkedList的第一個元素
    public E getFirst() {
        if (size==0)
            throw new NoSuchElementException();

        // 連結串列的表頭header中不包含資料。
        // 這裡返回header所指下一個節點所包含的資料。
        return header.next.element;
    }

    // 獲取LinkedList的最後一個元素
    public E getLast()  {
        if (size==0)
            throw new NoSuchElementException();

        // 由於LinkedList是雙向連結串列;而表頭header不包含資料。
        // 因而,這裡返回表頭header的前一個節點所包含的資料。
        return header.previous.element;
    }

    // 刪除LinkedList的第一個元素
    public E removeFirst() {
        return remove(header.next);
    }

    // 刪除LinkedList的最後一個元素
    public E removeLast() {
        return remove(header.previous);
    }

    // 將元素新增到LinkedList的起始位置
    public void addFirst(E e) {
        addBefore(e, header.next);
    }

    // 將元素新增到LinkedList的結束位置
    public void addLast(E e) {
        addBefore(e, header);
    }

    // 判斷LinkedList是否包含元素(o)
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    // 返回LinkedList的大小
    public int size() {
        return size;
    }

    // 將元素(E)新增到LinkedList中
    public boolean add(E e) {
        // 將節點(節點資料是e)新增到表頭(header)之前。
        // 即,將節點新增到雙向連結串列的末端。
        addBefore(e, header);
        return true;
    }

    // 從LinkedList中刪除元素(o)
    // 從連結串列開始查詢,如存在元素(o)則刪除該元素並返回true;
    // 否則,返回false。
    public boolean remove(Object o) {
        if (o==null) {
            // 若o為null的刪除情況
            for (Entry<E> e = header.next; e != header; e = e.next) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            // 若o不為null的刪除情況
            for (Entry<E> e = header.next; e != header; e = e.next) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

    // 將“集合(c)”新增到LinkedList中。
    // 實際上,是從雙向連結串列的末尾開始,將“集合(c)”新增到雙向連結串列中。
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    // 從雙向連結串列的index開始,將“集合(c)”新增到雙向連結串列中。
    public boolean addAll(int index, Collection<? extends E> c) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Object[] a = c.toArray();
        // 獲取集合的長度
        int numNew = a.length;
        if (numNew==0)
            return false;
        modCount++;

        // 設定“當前要插入節點的後一個節點”
        Entry<E> successor = (index==size ? header : entry(index));
        // 設定“當前要插入節點的前一個節點”
        Entry<E> predecessor = successor.previous;
        // 將集合(c)全部插入雙向連結串列中
        for (int i=0; i<numNew; i++) {
            Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
            predecessor.next = e;
            predecessor = e;
        }
        successor.previous = predecessor;

        // 調整LinkedList的實際大小
        size += numNew;
        return true;
    }

    // 清空雙向連結串列
    public void clear() {
        Entry<E> e = header.next;
        // 從表頭開始,逐個向後遍歷;對遍歷到的節點執行一下操作:
        // (01) 設定前一個節點為null 
        // (02) 設定當前節點的內容為null 
        // (03) 設定後一個節點為“新的當前節點”
        while (e != header) {
            Entry<E> next = e.next;
            e.next = e.previous = null;
            e.element = null;
            e = next;
        }
        header.next = header.previous = header;
        // 設定大小為0
        size = 0;
        modCount++;
    }

    // 返回LinkedList指定位置的元素
    public E get(int index) {
        return entry(index).element;
    }

    // 設定index位置對應的節點的值為element
    public E set(int index, E element) {
        Entry<E> e = entry(index);
        E oldVal = e.element;
        e.element = element;
        return oldVal;
    }
 
    // 在index前新增節點,且節點的值為element
    public void add(int index, E element) {
        addBefore(element, (index==size ? header : entry(index)));
    }

    // 刪除index位置的節點
    public E remove(int index) {
        return remove(entry(index));
    }

    // 獲取雙向連結串列中指定位置的節點
    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;
    }

    // 從前向後查詢,返回“值為物件(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;
    }

    // 從後向前查詢,返回“值為物件(o)的節點對應的索引”
    // 不存在就返回-1
    public int lastIndexOf(Object o) {
        int index = size;
        if (o==null) {
            for (Entry e = header.previous; e != header; e = e.previous) {
                index--;
                if (e.element==null)
                    return index;
            }
        } else {
            for (Entry e = header.previous; e != header; e = e.previous) {
                index--;
                if (o.equals(e.element))
                    return index;
            }
        }
        return -1;
    }

    // 返回第一個節點
    // 若LinkedList的大小為0,則返回null
    public E peek() {
        if (size==0)
            return null;
        return getFirst();
    }

    // 返回第一個節點
    // 若LinkedList的大小為0,則丟擲異常
    public E element() {
        return getFirst();
    }

    // 刪除並返回第一個節點
    // 若LinkedList的大小為0,則返回null
    public E poll() {
        if (size==0)
            return null;
        return removeFirst();
    }

    // 將e新增雙向連結串列末尾
    public boolean offer(E e) {
        return add(e);
    }

    // 將e新增雙向連結串列開頭
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    // 將e新增雙向連結串列末尾
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    // 返回第一個節點
    // 若LinkedList的大小為0,則返回null
    public E peekFirst() {
        if (size==0)
            return null;
        return getFirst();
    }

    // 返回最後一個節點
    // 若LinkedList的大小為0,則返回null
    public E peekLast() {
        if (size==0)
            return null;
        return getLast();
    }

    // 刪除並返回第一個節點
    // 若LinkedList的大小為0,則返回null
    public E pollFirst() {
        if (size==0)
            return null;
        return removeFirst();
    }

    // 刪除並返回最後一個節點
    // 若LinkedList的大小為0,則返回null
    public E pollLast() {
        if (size==0)
            return null;
        return removeLast();
    }

    // 將e插入到雙向連結串列開頭
    public void push(E e) {
        addFirst(e);
    }

    // 刪除並返回第一個節點
    public E pop() {
        return removeFirst();
    }

    // 從LinkedList開始向後查詢,刪除第一個值為元素(o)的節點
    // 從連結串列開始查詢,如存在節點的值為元素(o)的節點,則刪除該節點
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    // 從LinkedList末尾向前查詢,刪除第一個值為元素(o)的節點
    // 從連結串列開始查詢,如存在節點的值為元素(o)的節點,則刪除該節點
    public boolean removeLastOccurrence(Object o) {
        if (o==null) {
            for (Entry<E> e = header.previous; e != header; e = e.previous) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            for (Entry<E> e = header.previous; e != header; e = e.previous) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

    // 返回“index到末尾的全部節點”對應的ListIterator物件(List迭代器)
    public ListIterator<E> listIterator(int index) {
        return new ListItr(index);
    }

    // List迭代器
    private class ListItr implements ListIterator<E> {
        // 上一次返回的節點
        private Entry<E> lastReturned = header;
        // 下一個節點
        private Entry<E> next;
        // 下一個節點對應的索引值
        private int nextIndex;
        // 期望的改變計數。用來實現fail-fast機制。
        private int expectedModCount = modCount;

        // 建構函式。
        // 從index位置開始進行迭代
        ListItr(int index) {
            // index的有效性處理
            if (index < 0 || index > size)
                throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);
            // 若 “index 小於 ‘雙向連結串列長度的一半’”,則從第一個元素開始往後查詢;
            // 否則,從最後一個元素往前查詢。
            if (index < (size >> 1)) {
                next = header.next;
                for (nextIndex=0; nextIndex<index; nextIndex++)
                    next = next.next;
            } else {
                next = header;
                for (nextIndex=size; nextIndex>index; nextIndex--)
                    next = next.previous;
            }
        }

        // 是否存在下一個元素
        public boolean hasNext() {
            // 通過元素索引是否等於“雙向連結串列大小”來判斷是否達到最後。
            return nextIndex != size;
        }

        // 獲取下一個元素
        public E next() {
            checkForComodification();
            if (nextIndex == size)
                throw new NoSuchElementException();

            lastReturned = next;
            // next指向連結串列的下一個元素
            next = next.next;
            nextIndex++;
            return lastReturned.element;
        }

        // 是否存在上一個元素
        public boolean hasPrevious() {
            // 通過元素索引是否等於0,來判斷是否達到開頭。
            return nextIndex != 0;
        }

        // 獲取上一個元素
        public E previous() {
            if (nextIndex == 0)
            throw new NoSuchElementException();

            // next指向連結串列的上一個元素
            lastReturned = next = next.previous;
            nextIndex--;
            checkForComodification();
            return lastReturned.element;
        }

        // 獲取下一個元素的索引
        public int nextIndex() {
            return nextIndex;
        }

        // 獲取上一個元素的索引
        public int previousIndex() {
            return nextIndex-1;
        }

        // 刪除當前元素。
        // 刪除雙向連結串列中的當前節點
        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++;
        }

        // 設定當前節點為e
        public void set(E e) {
            if (lastReturned == header)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.element = e;
        }

        // 將e新增到當前節點的前面
        public void add(E e) {
            checkForComodification();
            lastReturned = header;
            addBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        // 判斷 “modCount和expectedModCount是否相等”,依次來實現fail-fast機制。
        final void checkForComodification() {
            if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        }
    }

    // 雙向連結串列的節點所對應的資料結構。
    // 包含3部分:上一節點,下一節點,當前節點值。
    private static class Entry<E> {
        // 當前節點所包含的值
        E element;
        // 下一個節點
        Entry<E> next;
        // 上一個節點
        Entry<E> previous;

        /**
         * 連結串列節點的建構函式。
         * 引數說明:
         *   element  —— 節點所包含的資料
         *   next      —— 下一個節點
         *   previous —— 上一個節點
         */
        Entry(E element, Entry<E> next, Entry<E> previous) {
            this.element = element;
            this.next = next;
            this.previous = previous;
        }
    }

    // 將節點(節點資料是e)新增到entry節點之前。
    private Entry<E> addBefore(E e, Entry<E> entry) {
        // 新建節點newEntry,將newEntry插入到節點e之前;並且設定newEntry的資料是e
        Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
        newEntry.previous.next = newEntry;
        newEntry.next.previous = newEntry;
        // 修改LinkedList大小
        size++;
        // 修改LinkedList的修改統計數:用來實現fail-fast機制。
        modCount++;
        return newEntry;
    }

    // 將節點從連結串列中刪除
    private E remove(Entry<E> e) {
        if (e == header)
            throw new NoSuchElementException();

        E result = e.element;
        e.previous.next = e.next;
        e.next.previous = e.previous;
        e.next = e.previous = null;
        e.element = null;
        size--;
        modCount++;
        return result;
    }

    // 反向迭代器
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    // 反向迭代器實現類。
    private class DescendingIterator implements Iterator {
        final ListItr itr = new ListItr(size());
        // 反向迭代器是否下一個元素。
        // 實際上是判斷雙向連結串列的當前節點是否達到開頭
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        // 反向迭代器獲取下一個元素。
        // 實際上是獲取雙向連結串列的前一個節點
        public E next() {
            return itr.previous();
        }
        // 刪除當前節點
        public void remove() {
            itr.remove();
        }
    }


    // 返回LinkedList的Object[]陣列
    public Object[] toArray() {
    // 新建Object[]陣列
    Object[] result = new Object[size];
        int i = 0;
        // 將連結串列中所有節點的資料都新增到Object[]陣列中
        for (Entry<E> e = header.next; e != header; e = e.next)
            result[i++] = e.element;
    return result;
    }

    // 返回LinkedList的模板陣列。所謂模板陣列,即可以將T設為任意的資料型別
    public <T> T[] toArray(T[] a) {
        // 若陣列a的大小 < LinkedList的元素個數(意味著陣列a不能容納LinkedList中全部元素)
        // 則新建一個T[]陣列,T[]的大小為LinkedList大小,並將該T[]賦值給a。
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        // 將連結串列中所有節點的資料都新增到陣列a中
        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;
    }


    // 克隆函式。返回LinkedList的克隆物件。
    public Object clone() {
        LinkedList<E> clone = null;
        // 克隆一個LinkedList克隆物件
        try {
            clone = (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }

        // 新建LinkedList表頭節點
        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;
    }

    // java.io.Serializable的寫入函式
    // 將LinkedList的“容量,所有的元素值”都寫入到輸出流中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // 寫入“容量”
        s.writeInt(size);

        // 將連結串列中所有節點的資料都寫入到輸出流中
        for (Entry e = header.next; e != header; e = e.next)
            s.writeObject(e.element);
    }

    // java.io.Serializable的讀取函式:根據寫入方式反向讀出
    // 先將LinkedList的“容量”讀出,然後將“所有的元素值”讀出
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // 從輸入流中讀取“容量”
        int size = s.readInt();

        // 新建連結串列表頭節點
        header = new Entry<E>(null, null, null);
        header.next = header.previous = header;

        // 從輸入流中將“所有的元素值”並逐個新增到連結串列中
        for (int i=0; i<size; i++)
            addBefore((E)s.readObject(), header);
    }

}

 

總結:1,LinkedList是通過雙向連結串列實現,他包含一個重要的內部類,Entry,Entry是雙向連結串列節點所對應的資料結構,它包含的屬性有,previous,element,next。

2,LinkedList不存在容量不足的情況

3,LinkedList的克隆函式,就是將全部元素克隆到新的LinkedList物件中

4,LinkedList實現Serializable,當寫入到輸出流時,先寫入容量,然後依次寫入每一個節點包含的值,當讀出輸入流時,限度去容量,再依次讀取每一個元素

5,由於LinkedList實現了Deque,而Deque介面定義了在雙端佇列兩端訪問元素的方法。提供插入、移除和檢查元素的方法。每種方法都存在兩種形式:一種形式在操作失敗時丟擲異常,另一種形式返回一個特殊值(null 或 false,具體取決於操作)。

        第一個元素(頭部)                 最後一個元素(尾部)
        丟擲異常        特殊值            丟擲異常        特殊值
插入    addFirst(e)    offerFirst(e)    addLast(e)        offerLast(e)
移除    removeFirst()  pollFirst()      removeLast()    pollLast()
檢查    getFirst()     peekFirst()      getLast()        peekLast()

 6,LinkedList可以作為FIFO(先進先出)的佇列,作為FIFO的佇列時,下表的方法等價:

佇列方法       等效方法
add(e)        addLast(e)
offer(e)      offerLast(e)
remove()      removeFirst()
poll()        pollFirst()
element()     getFirst()
peek()        peekFirst()

7,LinkedList可以作為LIFO(後進先出)的棧,作為LIFO的棧時,下表的方法等價:

棧方法        等效方法
push(e)      addFirst(e)
pop()        removeFirst()
peek()       peekFirst()

LinkedList遍歷方式

  • for迴圈快速隨機訪問,foreach遍歷,Iterator迭代器,PollFirst,PollLast,RemoveLast,RemoveFirst 
public class LinkedListTest {  
    public static void main(String[] args) {  
        LinkedList<Integer> llist = new LinkedList<Integer>();  
        for (int i=0; i<100000; i++)  
            llist.addLast(i);  
          
        byCommonFor(llist) ;// 通過一般for迴圈來遍歷LinkedList  
        byForEach(llist) ;  // 通過for-each來遍歷LinkedList  
        byIterator(llist) ; // 通過Iterator來遍歷LinkedList  
        byPollFirst(llist) ;    // 通過PollFirst()遍歷LinkedList     
        byPollLast(llist) ; // 通過PollLast()遍歷LinkedList   
        byRemoveFirst(llist) ;   // 通過removeFirst()遍歷LinkedList     
        byRemoveLast(llist) ; // 通過removeLast()遍歷LinkedList  
    }  
      
   
    private static void byCommonFor(LinkedList<Integer> list) {// 通過一般for迴圈來遍歷LinkedList  
        if (list == null)  
            return ;  
        long start = System.currentTimeMillis();       
        int size = list.size();  
        for (int i=0; i<size; i++) {  
            list.get(i);          
        }  
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byCommonFor------->" + total+" ms");  
    }  
      
    private static void byForEach(LinkedList<Integer> list) {// 通過for-each來遍歷LinkedList  
        if (list == null)  
            return ;   
        long start = System.currentTimeMillis();         
        for (Integer integ:list)   
            ;   
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byForEach------->" + total+" ms");  
    }  
   
    private static void byIterator(LinkedList<Integer> list) {// 通過Iterator來遍歷LinkedList  
        if (list == null)  
            return ;   
        long start = System.currentTimeMillis();       
        for(Iterator iter = list.iterator(); iter.hasNext();)  
            iter.next();   
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byIterator------->" + total+" ms");  
    }  
   
    private static void byPollFirst(LinkedList<Integer> list) {//通過PollFirst()遍歷LinkedList     
        if (list == null)  
            return ;   
        long start = System.currentTimeMillis();  
        while(list.pollFirst() != null)  
            ;   
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byPollFirst------->" + total+" ms");  
    }  
   
    private static void byPollLast(LinkedList<Integer> list) {// 通過PollLast()遍歷LinkedList   
        if (list == null)  
            return ;   
        long start = System.currentTimeMillis();  
        while(list.pollLast() != null)  
            ;   
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byPollLast------->" + total+" ms");  
    }  
   
    private static void byRemoveFirst(LinkedList<Integer> list) {// 通過removeFirst()遍歷LinkedList  
        if (list == null)  
            return ;   
        long start = System.currentTimeMillis();  
        try {  
            while(list.removeFirst() != null)  
                ;  
        } catch (NoSuchElementException e) {  
        }   
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byRemoveFirst------->" + total+" ms");  
    }  
   
    private static void byRemoveLast(LinkedList<Integer> list) {// 通過removeLast()遍歷LinkedList  
        if (list == null)  
            return ;  
        long start = System.currentTimeMillis();  
        try {  
            while(list.removeLast() != null)  
                ;  
        } catch (NoSuchElementException e) {  
        }  
        long end = System.currentTimeMillis();  
        long total = end - start;  
        System.out.println("byRemoveLast------->" + total+" ms");  
    }  
  
}  

byCommonFor------->5342 ms
byForEach------->11 ms
byIterator------->8 ms
byPollFirst------->4 ms
byPollLast------->0 ms
byRemoveFirst------->0 ms
byRemoveLast------->0 ms
由此可見,遍歷LinkedList時,使用removeFist()或removeLast()效率最高。但用它們遍歷時,會刪除原始資料;若單純只讀取,而不刪除,LinkedList遍歷時建議使用For-each或者迭代器的方式。千萬不要通過隨機訪問去遍歷LinkedList

LinkedList示例

import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;

/*
 * @desc LinkedList測試程式。
 *
 * @author skywang
 * @email  [email protected]
 */
public class LinkedListTest {
    public static void main(String[] args) {
        // 測試LinkedList的API
        testLinkedListAPIs() ;

        // 將LinkedList當作 LIFO(後進先出)的堆疊
        useLinkedListAsLIFO();

        // 將LinkedList當作 FIFO(先進先出)的佇列
        useLinkedListAsFIFO();
    }
    
    /*
     * 測試LinkedList中部分API
     */
    private static void testLinkedListAPIs() {
        String val = null;
        //LinkedList llist;
        //llist.offer("10");
        // 新建一個LinkedList
        LinkedList llist = new LinkedList();
        //---- 新增操作 ----
        // 依次新增1,2,3
        llist.add("1");
        llist.add("2");
        llist.add("3");

        // 將“4”新增到第一個位置
        llist.add(1, "4");
        

        System.out.println("\nTest \"addFirst(), removeFirst(), getFirst()\"");
        // (01) 將“10”新增到第一個位置。  失敗的話,丟擲異常!
        llist.addFirst("10");
        System.out.println("llist:"+llist);
        // (02) 將第一個元素刪除。        失敗的話,丟擲異常!
        System.out.println("llist.removeFirst():"+llist.removeFirst());
        System.out.println("llist:"+llist);
        // (03) 獲取第一個元素。          失敗的話,丟擲異常!
        System.out.println("llist.getFirst():"+llist.getFirst());


        System.out.println("\nTest \"offerFirst(), pollFirst(), peekFirst()\"");
        // (01) 將“10”新增到第一個位置。  返回true。
        llist.offerFirst("10");
        System.out.println("llist:"+llist);
        // (02) 將第一個元素刪除。        失敗的話,返回null。
        System.out.println("llist.pollFirst():"+llist.pollFirst());
        System.out.println("llist:"+llist);
        // (03) 獲取第一個元素。          失敗的話,返回null。
        System.out.println("llist.peekFirst():"+llist.peekFirst());
    

        System.out.println("\nTest \"addLast(), removeLast(), getLast()\"");
        // (01) 將“20”新增到最後一個位置。  失敗的話,丟擲異常!
        llist.addLast("20");
        System.out.println("llist:"+llist);
        // (02) 將最後一個元素刪除。        失敗的話,丟擲異常!
        System.out.println("llist.removeLast():"+llist.removeLast());
        System.out.println("llist:"+llist);
        // (03) 獲取最後一個元素。          失敗的話,丟擲異常!
        System.out.println("llist.getLast():"+llist.getLast());


        System.out.println("\nTest \"offerLast(), pollLast(), peekLast()\"");
        // (01) 將“20”新增到第一個位置。  返回true。
        llist.offerLast("20");
        System.out.println("llist:"+llist);
        // (02) 將第一個元素刪除。        失敗的話,返回null。
        System.out.println("llist.pollLast():"+llist.pollLast());
        System.out.println("llist:"+llist);
        // (03) 獲取第一個元素。          失敗的話,返回null。
        System.out.println("llist.peekLast():"+llist.peekLast());

         

        // 將第3個元素設定300。不建議在LinkedList中使用此操作,因為效率低!
        llist.set(2, "300");
        // 獲取第3個元素。不建議在LinkedList中使用此操作,因為效率低!
        System.out.println("\nget(3):"+llist.get(2));


        // ---- toArray(T[] a) ----
        // 將LinkedList轉行為陣列
        String[] arr = (String[])llist.toArray(new String[0]);
        for (String str:arr) 
            System.out.println("str:"+str);

        // 輸出大小
        System.out.println("size:"+llist.size());
        // 清空LinkedList
        llist.clear();
        // 判斷LinkedList是否為空
        System.out.println("isEmpty():"+llist.isEmpty()+"\n");

    }

    /**
     * 將LinkedList當作 LIFO(後進先出)的堆疊
     */
    private static void useLinkedListAsLIFO() {
        System.out.println("\nuseLinkedListAsLIFO");
        // 新建一個LinkedList
        LinkedList stack = new LinkedList();

        // 將1,2,3,4新增到堆疊中
        stack.push("1");
        stack.push("2");
        stack.push("3");
        stack.push("4");
        // 列印“棧”
        System.out.println("stack:"+stack);

        // 刪除“棧頂元素”
        System.out.println("stack.pop():"+stack.pop());
        
        // 取出“棧頂元素”
        System.out.println("stack.peek():"+stack.peek());

        // 列印“棧”
        System.out.println("stack:"+stack);
    }

    /**
     * 將LinkedList當作 FIFO(先進先出)的佇列
     */
    private static void useLinkedListAsFIFO() {
        System.out.println("\nuseLinkedListAsFIFO");
        // 新建一個LinkedList
        LinkedList queue = new LinkedList();

        // 將10,20,30,40新增到佇列。每次都是插入到末尾
        queue.add("10");
        queue.add("20");
        queue.add("30");
        queue.add("40");
        // 列印“佇列”
        System.out.println("queue:"+queue);

        // 刪除(佇列的第一個元素)
        System.out.println("queue.remove():"+queue.remove());
    
        // 讀取(佇列的第一個元素)
        System.out.println("queue.element():"+queue.element());

        // 列印“佇列”
        System.out.println("queue:"+queue);
    }
}

結果:

Test "addFirst(), removeFirst(), getFirst()"
llist:[10, 1, 4, 2, 3]
llist.removeFirst():10
llist:[1, 4, 2, 3]
llist.getFirst():1

Test "offerFirst(), pollFirst(), peekFirst()"
llist:[10, 1, 4, 2, 3]
llist.pollFirst():10
llist:[1, 4, 2, 3]
llist.peekFirst():1

Test "addLast(), removeLast(), getLast()"
llist:[1, 4, 2, 3, 20]
llist.removeLast():20
llist:[1, 4, 2, 3]
llist.getLast():3

Test "offerLast(), pollLast(), peekLast()"
llist:[1, 4, 2, 3, 20]
llist.pollLast():20
llist:[1, 4, 2, 3]
llist.peekLast():3

get(3):300
str:1
str:4
str:300
str:3
size:4
isEmpty():true


useLinkedListAsLIFO
stack:[4, 3, 2, 1]
stack.pop():4
stack.peek():3
stack:[3, 2, 1]

useLinkedListAsFIFO
queue:[10, 20, 30, 40]
queue.remove():10
queue.element():20
queue:[20, 30, 40]

 可以看出,LinkedList可以作為FIFO(先進先出)的佇列,作為FIFO的佇列時,下表的方法等價:

佇列方法       等效方法
add(e)        addLast(e)
offer(e)      offerLast(e)
remove()      removeFirst()
poll()        pollFirst()
element()     getFirst()
peek()        peekFirst()

LinkedList可以作為LIFO(後進先出)的棧,作為LIFO的棧時,下表的方法等價:

棧方法        等效方法
push(e)      addFirst(e)
pop()        removeFirst()
peek()       peekFirst()