亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Java 集合系列05之 LinkedList詳細(xì)介紹

Original 2016-11-08 13:14:30 321
abstrakt:概要 前面,我們已經(jīng)學(xué)習(xí)了ArrayList,并了解了fail-fast機(jī)制。這一章我們接著學(xué)習(xí)List的實(shí)現(xiàn)類——LinkedList。和學(xué)習(xí)ArrayList一樣,接下來呢,我們先對LinkedList有個整體認(rèn)識,然后再學(xué)習(xí)它的源碼;最后再通過實(shí)例來學(xué)會使用LinkedList。內(nèi)容包括:第1部分 LinkedList介紹第2部分 LinkedList數(shù)據(jù)結(jié)構(gòu)第3部分 Linked

概要 

前面,我們已經(jīng)學(xué)習(xí)了ArrayList,并了解了fail-fast機(jī)制。這一章我們接著學(xué)習(xí)List的實(shí)現(xiàn)類——LinkedList。

和學(xué)習(xí)ArrayList一樣,接下來呢,我們先對LinkedList有個整體認(rèn)識,然后再學(xué)習(xí)它的源碼;最后再通過實(shí)例來學(xué)會使用LinkedList。內(nèi)容包括:

第1部分 LinkedList介紹

第2部分 LinkedList數(shù)據(jù)結(jié)構(gòu)

第3部分 LinkedList源碼解析(基于JDK1.6.0_45)

第4部分 LinkedList遍歷方式

第5部分 LinkedList示例

第1部分 LinkedList介紹

LinkedList簡介

LinkedList 是一個繼承于AbstractSequentialList的雙向鏈表。它也可以被當(dāng)作堆棧、隊(duì)列或雙端隊(duì)列進(jìn)行操作。

LinkedList 實(shí)現(xiàn) List 接口,能對它進(jìn)行隊(duì)列操作。

LinkedList 實(shí)現(xiàn) Deque 接口,即能將LinkedList當(dāng)作雙端隊(duì)列使用。

LinkedList 實(shí)現(xiàn)了Cloneable接口,即覆蓋了函數(shù)clone(),能克隆。

LinkedList 實(shí)現(xiàn)java.io.Serializable接口,這意味著LinkedList支持序列化,能通過序列化去傳輸。

LinkedList 是非同步的。

LinkedList構(gòu)造函數(shù)

// 默認(rèn)構(gòu)造函數(shù)
LinkedList()
// 創(chuàng)建一個LinkedList,保護(hù)Collection中的全部元素。
LinkedList(Collection<? extends E> collection)

LinkedList的API 

LinkedList的API
boolean       add(E object)
void          add(int location, E object)
boolean       addAll(Collection<? extends E> collection)
boolean       addAll(int location, Collection<? extends E> collection)
void          addFirst(E object)
void          addLast(E object)
void          clear()
Object        clone()
boolean       contains(Object object)
Iterator<E>   descendingIterator()
E             element()
E             get(int location)
E             getFirst()
E             getLast()
int           indexOf(Object object)
int           lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
boolean       offer(E o)
boolean       offerFirst(E e)
boolean       offerLast(E e)
E             peek()
E             peekFirst()
E             peekLast()
E             poll()
E             pollFirst()
E             pollLast()
E             pop()
void          push(E e)
E             remove()
E             remove(int location)
boolean       remove(Object object)
E             removeFirst()
boolean       removeFirstOccurrence(Object o)
E             removeLast()
boolean       removeLastOccurrence(Object o)
E             set(int location, E object)
int           size()
<T> T[]       toArray(T[] contents)
Object[]     toArray()

AbstractSequentialList簡介

在介紹LinkedList的源碼之前,先介紹一下AbstractSequentialList。畢竟,LinkedList是AbstractSequentialList的子類。

AbstractSequentialList 實(shí)現(xiàn)了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)這些函數(shù)。這些接口都是隨機(jī)訪問List的,LinkedList是雙向鏈表;既然它繼承于AbstractSequentialList,就相當(dāng)于已經(jīng)實(shí)現(xiàn)了“get(int index)這些接口”。

此外,我們?nèi)粜枰ㄟ^AbstractSequentialList自己實(shí)現(xiàn)一個列表,只需要擴(kuò)展此類,并提供 listIterator() 和 size() 方法的實(shí)現(xiàn)即可。若要實(shí)現(xiàn)不可修改的列表,則需要實(shí)現(xiàn)列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。

第2部分 LinkedList數(shù)據(jù)結(jié)構(gòu)

LinkedList的繼承關(guān)系

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關(guān)系如下圖:

4.jpg



LinkedList的本質(zhì)是雙向鏈表。

(01) LinkedList繼承于AbstractSequentialList,并且實(shí)現(xiàn)了Dequeue接口。 

(02) LinkedList包含兩個重要的成員:header 和 size。

  header是雙向鏈表的表頭,它是雙向鏈表節(jié)點(diǎn)所對應(yīng)的類Entry的實(shí)例。Entry中包含成員變量: previous, next, element。其中,previous是該節(jié)點(diǎn)的上一個節(jié)點(diǎn),next是該節(jié)點(diǎn)的下一個節(jié)點(diǎn),element是該節(jié)點(diǎn)所包含的值。 

  size是雙向鏈表中節(jié)點(diǎn)的個數(shù)。

第3部分 LinkedList源碼解析(基于JDK1.6.0_45)

為了更了解LinkedList的原理,下面對LinkedList源碼代碼作出分析。

在閱讀源碼之前,我們先對LinkedList的整體實(shí)現(xiàn)進(jìn)行大致說明:

    LinkedList實(shí)際上是通過雙向鏈表去實(shí)現(xiàn)的。既然是雙向鏈表,那么它的順序訪問會非常高效,而隨機(jī)訪問效率比較低。

    既然LinkedList是通過雙向鏈表的,但是它也實(shí)現(xiàn)了List接口{也就是說,它實(shí)現(xiàn)了get(int location)、remove(int location)等“根據(jù)索引值來獲取、刪除節(jié)點(diǎn)的函數(shù)”}。LinkedList是如何實(shí)現(xiàn)List的這些接口的,如何將“雙向鏈表和索引值聯(lián)系起來的”?

    實(shí)際原理非常簡單,它就是通過一個計(jì)數(shù)索引值來實(shí)現(xiàn)的。例如,當(dāng)我們調(diào)用get(int location)時,首先會比較“l(fā)ocation”和“雙向鏈表長度的1/2”;若前者大,則從鏈表頭開始往后查找,直到location位置;否則,從鏈表末尾開始先前查找,直到location位置。

   這就是“雙線鏈表和索引值聯(lián)系起來”的方法。

好了,接下來開始閱讀源碼(只要理解雙向鏈表,那么LinkedList的源碼很容易理解的)。

package java.util;

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    // 鏈表的表頭,表頭不包含任何數(shù)據(jù)。Entry是個鏈表類數(shù)據(jù)結(jié)構(gòu)。
    private transient Entry<E> header = new Entry<E>(null, null, null);

    // LinkedList中元素個數(shù)
    private transient int size = 0;

    // 默認(rèn)構(gòu)造函數(shù):創(chuàng)建一個空的鏈表
    public LinkedList() {
        header.next = header.previous = header;
    }

    // 包含“集合”的構(gòu)造函數(shù):創(chuàng)建一個包含“集合”的LinkedList
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

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

        // 鏈表的表頭header中不包含數(shù)據(jù)。
        // 這里返回header所指下一個節(jié)點(diǎn)所包含的數(shù)據(jù)。
        return header.next.element;
    }

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

        // 由于LinkedList是雙向鏈表;而表頭header不包含數(shù)據(jù)。
        // 因而,這里返回表頭header的前一個節(jié)點(diǎn)所包含的數(shù)據(jù)。
        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的結(jié)束位置
    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) {
        // 將節(jié)點(diǎn)(節(jié)點(diǎn)數(shù)據(jù)是e)添加到表頭(header)之前。
        // 即,將節(jié)點(diǎn)添加到雙向鏈表的末端。
        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中。
    // 實(shí)際上,是從雙向鏈表的末尾開始,將“集合(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++;

        // 設(shè)置“當(dāng)前要插入節(jié)點(diǎn)的后一個節(jié)點(diǎn)”
        Entry<E> successor = (index==size ? header : entry(index));
        // 設(shè)置“當(dāng)前要插入節(jié)點(diǎn)的前一個節(jié)點(diǎn)”
        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;

        // 調(diào)整LinkedList的實(shí)際大小
        size += numNew;
        return true;
    }

    // 清空雙向鏈表
    public void clear() {
        Entry<E> e = header.next;
        // 從表頭開始,逐個向后遍歷;對遍歷到的節(jié)點(diǎn)執(zhí)行一下操作:
        // (01) 設(shè)置前一個節(jié)點(diǎn)為null 
        // (02) 設(shè)置當(dāng)前節(jié)點(diǎn)的內(nèi)容為null 
        // (03) 設(shè)置后一個節(jié)點(diǎn)為“新的當(dāng)前節(jié)點(diǎn)”
        while (e != header) {
            Entry<E> next = e.next;
            e.next = e.previous = null;
            e.element = null;
            e = next;
        }
        header.next = header.previous = header;
        // 設(shè)置大小為0
        size = 0;
        modCount++;
    }

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

    // 設(shè)置index位置對應(yīng)的節(jié)點(diǎn)的值為element
    public E set(int index, E element) {
        Entry<E> e = entry(index);
        E oldVal = e.element;
        e.element = element;
        return oldVal;
    }
 
    // 在index前添加節(jié)點(diǎn),且節(jié)點(diǎn)的值為element
    public void add(int index, E element) {
        addBefore(element, (index==size ? header : entry(index)));
    }

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

    // 獲取雙向鏈表中指定位置的節(jié)點(diǎn)
    private Entry<E> entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;
        // 獲取index處的節(jié)點(diǎn)。
        // 若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)的節(jié)點(diǎn)對應(yīng)的索引”
    // 不存在就返回-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)的節(jié)點(diǎn)對應(yīng)的索引”
    // 不存在就返回-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;
    }

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

    // 返回第一個節(jié)點(diǎn)
    // 若LinkedList的大小為0,則拋出異常
    public E element() {
        return getFirst();
    }

    // 刪除并返回第一個節(jié)點(diǎn)
    // 若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;
    }

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

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

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

    // 刪除并返回最后一個節(jié)點(diǎn)
    // 若LinkedList的大小為0,則返回null
    public E pollLast() {
        if (size==0)
            return null;
        return removeLast();
    }

    // 將e插入到雙向鏈表開頭
    public void push(E e) {
        addFirst(e);
    }

    // 刪除并返回第一個節(jié)點(diǎn)
    public E pop() {
        return removeFirst();
    }

    // 從LinkedList開始向后查找,刪除第一個值為元素(o)的節(jié)點(diǎn)
    // 從鏈表開始查找,如存在節(jié)點(diǎn)的值為元素(o)的節(jié)點(diǎn),則刪除該節(jié)點(diǎn)
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    // 從LinkedList末尾向前查找,刪除第一個值為元素(o)的節(jié)點(diǎn)
    // 從鏈表開始查找,如存在節(jié)點(diǎn)的值為元素(o)的節(jié)點(diǎn),則刪除該節(jié)點(diǎn)
    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到末尾的全部節(jié)點(diǎn)”對應(yīng)的ListIterator對象(List迭代器)
    public ListIterator<E> listIterator(int index) {
        return new ListItr(index);
    }

    // List迭代器
    private class ListItr implements ListIterator<E> {
        // 上一次返回的節(jié)點(diǎn)
        private Entry<E> lastReturned = header;
        // 下一個節(jié)點(diǎn)
        private Entry<E> next;
        // 下一個節(jié)點(diǎn)對應(yīng)的索引值
        private int nextIndex;
        // 期望的改變計(jì)數(shù)。用來實(shí)現(xiàn)fail-fast機(jī)制。
        private int expectedModCount = modCount;

        // 構(gòu)造函數(shù)。
        // 從index位置開始進(jìn)行迭代
        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() {
            // 通過元素索引是否等于“雙向鏈表大小”來判斷是否達(dá)到最后。
            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,來判斷是否達(dá)到開頭。
            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;
        }

        // 刪除當(dāng)前元素。
        // 刪除雙向鏈表中的當(dāng)前節(jié)點(diǎn)
        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++;
        }

        // 設(shè)置當(dāng)前節(jié)點(diǎn)為e
        public void set(E e) {
            if (lastReturned == header)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.element = e;
        }

        // 將e添加到當(dāng)前節(jié)點(diǎn)的前面
        public void add(E e) {
            checkForComodification();
            lastReturned = header;
            addBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        // 判斷 “modCount和expectedModCount是否相等”,依次來實(shí)現(xiàn)fail-fast機(jī)制。
        final void checkForComodification() {
            if (modCount != expectedModCount)
      &				
			
Versionshinweise

Beliebte Eintr?ge