LinkedList源碼

1 說明

  1. LinkedList是一個雙向鏈表,繼承看List接口和Duque接口。java

  2. LinkedList不是線程安全,確保線程安全方法
List list = Collections.synchronizedList(new LinkedList(...))

2 源碼分析

2.1 靜態內部類

LinkedList是一個鏈表,須要一個node類做爲節點,所以他在內部構建了一個靜態內部類。node

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

靜態內部類,該類不能直接訪問LinkedLIst的非靜態成員(屬性和方法),由於Java的約束:靜態方法不能直接訪問非靜態的成員。數組

2.2 add()方法

往==鏈表尾部==添加元素,boolean修飾,老是返回true安全

public boolean add(E e) {
    linkLast(e);
    return true;
}

再看linkLast(e)方法源碼分析

void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}

若是l爲空,則表示鏈表爲空,插入的元素做爲列表的第一個元素。
last是一個全局變量this

transient Node<E> last;

而後相應的size也增長。size也是一個全局變量線程

transient int size = 0;

這樣的話就能夠寫個獲取size的方法,因此的size的方法爲code

public int size() {
    return size;
}

2.3 get()方法

public E get(int index) {
    checkElementIndex(index); 
    return node(index).item;
}

==checkElementIndex(index)== 判斷尋找的索引是否越界,若是越界則拋出異常。
==node(index).item== 經過方法取得nod對象,而後取得item的值。對象

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;
    }
}

這裏經過位運算找出尋找範圍的中間值,若是小於中間值,則出鏈頭開始尋找,不然從鏈尾往回尋找。值得借鑑。繼承

2.4 toArray()方法

將列表轉成數組的一個橋樑方法

public Object[] toArray() {
    Object[] result = new Object[size];
    int i = 0;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    return result;
}

2.5 clear()方法

此調用返回後,列表將爲空

public void clear() {
    // Clearing all of the links between nodes is "unnecessary", but:
    // - helps a generational GC if the discarded nodes inhabit
    //   more than one generation
    // - is sure to free memory even if there is a reachable Iterator
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

能夠利用該方法清空list列表,達到list屢次複用的目的,減小內存花銷

相關文章
相關標籤/搜索