《Java集合類2》講解LinkedList

標題 : LinkedList

概述
LinkedList與ArrayList一樣實現List接口。 只是ArrayList是List接口的大小可變數組的實現;&LinkedList是List接口鏈表的實現。基於鏈表實現的方式使得LinkedList在插入和刪除時更優於ArrayList,而隨機訪問則沒有ArrayList效率快。

LinkedList實現所有可選的列表操作,並允許所有的元素包括null。
除了實現 List 接口外,LinkedList 類還爲在列表的開頭及結尾 get、remove 和 insert 元素提供了統一的命名方法。這些操作允許將連接列表用作堆棧、隊列或雙端隊列。

此類實現 Deque 接口,爲 add、poll 提供先進先出隊列操作,以及其他堆棧和雙端隊列操作。
所有操作都是按照雙重連接列表的需要執行的。在列表中編索引的操作將從開頭或結尾遍歷列表(從靠近指定索引的一端)。
同時,與ArrayList一樣此實現不是同步的。

源碼分析
1、LinkedList源碼定義:

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

從這段代碼中可以看出LinkedList繼承AbstractSequentialList,實現List、Deque、Cloneable、Serializable。其中AbstractSequentialList提供了 List 接口的骨幹實現,從而最大限度地減少了實現受“連續訪問”數據存儲(如鏈接列表)支持的此接口所需的工作,從而以減少實現List接口的複雜度。Deque一個線性 collection,支持在兩端插入和移除元素,定義了雙端隊列的操作。

2、兩個基本屬性:size、header

   transient int size = 0; 
   transient Entry header =new Entry(null,null,null);

其中size表示的LinkedList的大小,header表示鏈表的表頭,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;
    }
}
  上面爲Entry對象的源代碼,Entry爲LinkedList的內部類,它定義了存儲的元素。
  該元素的前一個元素、後一個元素,這是典型的雙向鏈表定義方式。

3、構造方法
LinkedList提供了兩個構造方法:LinkedList()和LinkedList(Collection<? extends E> c)

/**
 * 構造一個空列表.
 */
public LinkedList() {
}

/**
  * 構造一個包含指定 collection 中的元素的列表,這些元素按其 collection 的迭代器
  * 返回的順序排列.
 */
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

LinkedList()構造一個空列表。裏面沒有任何元素,僅僅只是將header節點的前一個元素、後一個元素都指向自身。
LinkedList(Collection<? extends E> c): 構造一個包含指定 collection 中的元素的列表,這些元素按其 collection 的迭代器返回的順序排列。該構造函數首先會調用LinkedList(),構造一個空列表,然後調用了addAll()方法將Collection中的所有元素添加到列表中。以下是addAll()的源代碼

/**
 *  添加指定 collection 中的所有元素到此列表的結尾,順序是指定 collection 的迭代器
 *  返回這些元素的順序。
 */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    
/**
 * 將指定 collection 中的所有元素從指定位置開始插入此列表。其中index表示在其中
 * 插入指定collection中第一個元素的索引
 */
public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);//檢查下標合法性

    Object[] a = c.toArray();
    int numNew = a.length;   //插入元素的個數
    //若插入的元素爲空,則返回false
    if (numNew == 0)
        return false;

    //獲取插入位置的節點succ,若插入的位置在size處,則是頭節點,否則獲取index位置處的節點
    //插入位置的前一個節點pred,在插入過程中需要修改該節點的next引用:指向插入的節點元素
    LinkedList.Node<E> pred, succ;
    if (index == size) {
        succ = null;
        pred = last;
    } else {
        succ = node(index);
        pred = succ.prev;
    }

    //執行插入動作
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        //構造一個節點newNode,這裏已經執行了插入節點動作同時修改了相鄰節點的指向引用
        LinkedList.Node<E> newNode = new LinkedList.Node<>(pred, e, null);
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        //修改插入位置的前一個節點,這樣做的目的是將插入位置右移一位,保證後續的元素
        //是插在該元素的後面,確保這些元素的順序
        pred = newNode;
    }

    if (succ == null) {
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }
    //修改容量大小
    size += numNew;
    modCount++;
    return true;
}addAll()方法中,涉及到了兩個方法:
  一個是checkPositionIndex(int index),該方法爲LinkedList的私有方法,主要是用來檢查下標合法性;
  另一個是node(int index),該方法主要是用來查找index位置的節點元素。
/*
 * 判斷下標合法性,合法就返回true,否則拋異常。
 */
private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
    return index >= 0 && index <= size;
}

/**
 * 返回指定位置(若存在)的節點元素
 */
    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;
    }
}

從該方法有兩個遍歷方向中就可以看出:LinkedList是雙向鏈表,這也是在構造方法中爲什麼需要將header的前、後節點均指向自己。
所以只需要知道:LinkedList是雙向鏈表。

LinkedList中幾個常用方法的源碼分析
【增】

/*
 * add(E e): 將指定元素添加到此列表的結尾。
 */
public boolean add(E e) {
    linkLast(e);
    return true;
}
   方法調用linkLast方法,然後直接返回true,對於linkLast()而已,它爲LinkedList的私有方法
/**
 * Links e as first element.
 */
private void linkFirst(E e) {
    final Node<E> f = first;
    //構造一個新結點 newEntry,
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    //修改newNode 的前後節點的引用,確保其鏈表的引用關係是正確的
    if (f == null)
        last = newNode;
    else
        f.prev = newNode;
    size++; //容量+1
    modCount++; //修改次數+1
}   

在linkLast方法中無非就是:構建一個新節點newNode ,然後修改其前後的引用。
LinkedList還提供了其他的增加方法:

  add(int index, E element):在此列表中指定的位置插入指定的元素。
  addAll(Collection<? extends E> c):添加指定 collection 中的所有元素到此列表的結尾,順序是指定 collection 的迭代器返回這些元素的順序。
  addAll(int index, Collection<? extends E> c):將指定 collection 中的所有元素從指定位置開始插入此列表。
  addFirst(E e): 將指定元素插入此列表的開頭。
  addLast(E e): 將指定元素添加到此列表的結尾。

【刪】

  remove(Object o):從此列表中移除首次出現的指定元素(如果存在)。該方法的源代碼如下:

public boolean remove(Object o) {
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

該方法首先會判斷移除的元素是否爲null,然後迭代這個鏈表找到該元素節點,最後調用remove(Node e),remove(Node e)是LinkedList中所有移除方法的基礎方法,如下:

/*
 * 從這個列表中刪除指定位置的元素。
 */
public E remove(int index) {
    checkElementIndex(index);//檢查下標的合法性,上面已經分析過
    return unlink(node(index));
}

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;
}
  clear(): 從此列表中移除所有元素。
  remove():獲取並移除此列表的頭(第一個元素)。
  remove(int index):移除此列表中指定位置處的元素。
  remove(Objec o):從此列表中移除首次出現的指定元素(如果存在)。
  removeFirst():移除並返回此列表的第一個元素。
  removeFirstOccurrence(Object o):從此列表中移除第一次出現的指定元素(從頭部到尾部遍歷列表時)。
  removeLast():移除並返回此列表的最後一個元素。
  removeLastOccurrence(Object o):從此列表中移除最後一次出現的指定元素(從頭部到尾部遍歷列表時)。

【改】

/*
 *  將指定的元素替換指定位置的元素; 
 */
public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

【查】

/**
 * 對於查找方法的源碼就是迭代,比對,然後就是返回當前值。
 * get(int index):返回此列表中指定位置處的元素。
 * getFirst():返回此列表的第一個元素。
 * getLast():返回此列表的最後一個元素。
 * indexOf(Object o):返回此列表中首次出現的指定元素的索引,如果此列表中不包含該元素,則返回 -1。
 * lastIndexOf(Object o):返回此列表中最後出現的指定元素的索引,如果此列表中不包含該元素,則返回 -1。
 */
public E get(int index) {
    checkElementIndex(index);//檢查下標的合法性,上面已經分析過
    return node(index).item; //查找index位置的節點元素。
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章