JAVA集合:LinkedList原始碼解析

Danielxf發表於2018-04-14

LinkedList

List中除了ArrayList最常用以外,LinkedList也比較常見,而且這兩種list的實現方式不一樣,具體實現看一下原始碼很容易就理解了(以下原始碼來自jdk1.8.0_20)

繼承結構

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
複製程式碼

LinkedList繼承了AbstractSequentialList,實現了List介面、Deque介面和java.io.Serializable介面,從它的繼承機構就能看出它是一種佇列的實現方式。

成員變數

  • 大小size
    transient int size = 0;

  • 第一個節點
    transient Node<E> first;

  • 最後一個節點
    transient Node<E> last;

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有一個空參建構函式和一個集合引數建構函式。

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);  //把集合中所有節點新增到list中
}
複製程式碼
public boolean addAll(Collection<? extends E> c) {
    return addAll(size, c);
}

public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);  //檢查下標合法性

    Object[] a = c.toArray();   //把集合轉換為陣列
    int numNew = a.length;      //新增元素數量
    if (numNew == 0)
        return false;

    Node<E> pred, succ;
    if (index == size) {    //把集合c插入到最後面
        succ = null;
        pred = last;
    } else {
        succ = node(index);     //插入中間
        pred = succ.prev;
    }

    for (Object o : a) {    //迴圈插入節點
        @SuppressWarnings("unchecked") E e = (E) o;
        Node<E> newNode = new Node<>(pred, e, null);
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        pred = newNode;
    }

    if (succ == null) {     //如果插入最後面,則last節點是最後一個插入的節點
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }

    size += numNew;     //list大小加上增加集合的元素數量
    modCount++;         //修改次數加1
    return true;
}

private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
    return index >= 0 && index <= size;     //比較index在0到size之間
}

/**
*   獲取下標為index的節點
*/
Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {      //如果index在前半部分,則從前迴圈
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {                        //如果index在後半部分,則從後迴圈
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}
複製程式碼

主要方法

  • add方法
    • add(E e),一個引數方法,預設新增到list最後面
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);     //新建node節點,pre指向list中的last節點
        last = newNode;
        if (l == null)          //如果list為空,新增節點賦值給first
            first = newNode;
        else
            l.next = newNode;   //如果不為空,list中的last指向新增節點,完成新增節點動作
        size++;
        modCount++;
    }
複製程式碼
    • add(int index, E element),把元素element新增到下標index位置
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)  //如果index等於size,新增到list最後面
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);  //插入到當前index上的節點和它的pred節點中間
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
複製程式碼
  • 還有增加集合的add方法,上面介紹過了,以及實現的Deque介面的addFirst(E e)和addLast(E e)方法
    • addAll(Collection<? extends E> c)
    • addAll(int index, Collection<? extends E> c)
    • addFirst(E e) linkFirst插入到最前面
    • addLast(E e) 和add(E e)一樣
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
複製程式碼
  • get方法
    • get(int index) //獲取下標index上的元素
    • getFirst() //獲取第一個元素(first節點的值)
    • getLast() //獲取最後一個元素(last節點的值)
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;    //node(index)獲取下標index的node節點
    }
複製程式碼
public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
複製程式碼
public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
複製程式碼
  • remove方法
    • remove()刪除第一個元素,直接呼叫的removeFirst()方法
    • remove(int index)刪除下標index上的元素,如果下邊越界,會拋IndexOutOfBoundsException異常
    • remove(Object o)刪除第一個匹配到的元素o
    • removeFirst()刪除第一個元素(如果list為空,會丟擲NoSuchElementException異常)
    • removeFirstOccurrence(Object o)直接呼叫remove(o)
    • removeLast()刪除最後一個元素(如果list為空,會丟擲NoSuchElementException異常)
    • removeLastOccurrence(Object o)刪除最後一個匹配到的元素
    public E remove() {
        return removeFirst();
    }
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // 斷開刪除節點的連線,幫助垃圾回收
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
    
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index)); //刪除下標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節點,即刪除當前節點
            first = next;
        } else {
            prev.next = next;   //否則,前一個節點的next指向下一個節點
            x.prev = null;
        }

        if (next == null) { //如果是尾節點,last指向前一個節點,即刪除當前節點
            last = prev;
        } else {
            next.prev = prev;   //否則,下一個節點的prev指向前一個節點
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
    
    /**
    * 刪除list中最前面的元素o(如果存在),從first節點往後迴圈查詢
    * null的equals方法總是返回false,所以需要分開判斷
    */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {    //從first節點往後迴圈,刪除第一個匹配的元素,結束迴圈
                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;
    }
    
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }
    
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    
    public boolean removeLastOccurrence(Object o) { //刪除list中最後面的元素o(如果存在),從last節點往前迴圈查詢即可
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
複製程式碼
  • peek方法,返回list中的第一個元素,不刪除,如果list為空,返回null
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
複製程式碼
  • poll方法,返回list中的第一個元素,並刪除,如果list為空,返回null
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
複製程式碼
    • peekFirst(),同peek()
    • peekLast(),返回最後一個元素,不刪除
    • pollFirst(),同poll()
    • pollLast(),返回最後一個元素,並刪除
  • push(E e)方法,新增元素,

    public void push(E e) {
        addFirst(e);
    }
複製程式碼
  • pop()方法,刪除list中的第一個元素,如果list為空,丟擲NoSuchElementException異常
    public E pop() {
        return removeFirst();
    }
複製程式碼
  • clear()方法,刪除list中的所有元素
    public void clear() {
        for (Node<E> x = first; x != null; ) {  //迴圈list,把item、next、prev賦值為null,幫助垃圾回收
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }
複製程式碼
  • clone()方法,複製一個相同的list
    public Object clone() {
        LinkedList<E> clone = superClone();

        // 初始化list的狀態
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // 把原list中的元素複製到新list中
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }
    
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }
複製程式碼
  • contains(Object o)方法,判斷list中是否包含元素o
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
複製程式碼
  • indexOf(Object o)方法,返回元素o的下標
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }
複製程式碼
  • set(int index, E element)方法,給下標index上的元素賦值,返回原有的值
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
複製程式碼
  • size方法,返回list大小
    public int size() {
        return size;
    }
複製程式碼
  • toArray()方法,把list中的元素複製到新陣列中並返回該陣列
    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;
    }
複製程式碼
  • toArray(T[] a)方法,把list中的元素複製到指定的陣列中
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }
複製程式碼

ListIterator迭代器

  • listIterator(int index)
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
複製程式碼

LinkedList中的迭代器,比較簡單,使用next、nextIndex、lastReturned變數做個標記。

    private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;
        }

        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex - 1;
        }

        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }

        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
複製程式碼

總結

  • ArrayList是以陣列的方式實現,而LinkedList是以連結串列的方式實現
  • LinkedList的原始碼相對簡單,很容易理解它的儲存結構,提供的方法以及實現。

相關文章