Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> LinkedList源碼解析

LinkedList源碼解析

編輯:關於Android編程

LinkedList特點
1.內部通過雙向鏈表存儲數據
2.插入、刪除不需要移動元素,只需要修改指針
3.實現了隊列、雙端隊列、棧
4.插入、刪除操作比較多的時候,推薦使用
5.獲取指定index位置的值效率低

所在包

package java.util;

繼承AbstractSequentialList抽象類
實現List、Deque、Cloneable、java.io.Serializable
Deque是雙端隊列接口

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

內部節點定義方式
可以看出是雙向鏈表,只有一個構造器,參數:前驅節點,當前節點值,後繼節點,節點構造好後,其前驅和後繼節點也構建好

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

        Node(Node prev, E element, Node next) {
            this.item = element;
            this.next = next;// 後繼節點
            this.prev = prev;// 前驅節點
        }
    }

三個重要參數:size,first,last

// 元素個數
    transient int size = 0;

    /**
     * 第一個節點
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node first;

    /**
     * 最後一個節點
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node last;

兩個構造器

    /**
     * 空構造器
     */
    public LinkedList() {
    }

    /**
     * 集合c中元素加入的LinkedList中 
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection c) {
        this();
        addAll(c);
    }

頭插入節點

    /**
     * 插入節點e作為第一個節點
     */
    private void linkFirst(E e) {
        final Node f = first;
        final Node newNode = new Node<>(null, e, f); // f 前插入 值為e的節點 
        first = newNode; // first指針指向當前新的節點
        if (f == null) // f 為空所有沒有元素,則last指向當前新的節點 
            last = newNode;
        else
            f.prev = newNode; // 建立f節點的前驅節點
        size++;// 個數+1 
        modCount++;
    }

尾部插入節點

     /**
     * 插入節點e作為最後一個節點
     */
    void linkLast(E e) {
        final Node l = last;
        final Node newNode = new Node<>(l, e, null); // l 後 插入節點值為 e的節點 
        last = newNode;// last指針指向當前新的最後節點
        if (l == null) // null 說明沒有元素,first指向當前新的節點
            first = newNode;
        else
            l.next = newNode;// 建立l 的後繼節點
        size++;
        modCount++;
    }

succ之前插入節點

     /**
     * succ 前插入節點 
     */
    void linkBefore(E e, Node succ) {
        // assert succ != null;
        final Node pred = succ.prev;
        final Node newNode = new Node<>(pred, e, succ); // 新建節點 newNode.next = succ newNode.prev = pred 
        succ.prev = newNode; // 建立前驅
        if (pred == null) // 空時候 
            first = newNode;
        else // 建立後繼
            pred.next = newNode;
        size++;
        modCount++;
    }

刪除第一個節點,並返回節點值

    /**
     * 刪除第一個節點,並返回節點值
     */
    private E unlinkFirst(Node f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node next = f.next; // 後繼節點
        f.item = null;
        f.next = null; // 垃圾回收
        first = next; // 更新first
        if (next == null) // 空 
            last = null;
        else
            next.prev = null; // 前驅為null
        size--;
        modCount++;
        return element;
    }

刪除最後一個節點,並返回節點值

    /**
     * 刪除最後一個節點,並返回節點值
     */
    private E unlinkLast(Node l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node prev = l.prev; // 前驅節點
        l.item = null;
        l.prev = null; // 垃圾回收 
        last = prev; // 更新last
        if (prev == null) // null 
            first = null;
        else // 後繼為null 
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

刪除節點 x 並返回節點值

    /**
     * 刪除節點 x 並返回節點值
     */
    E unlink(Node x) {
        // assert x != null;
        final E element = x.item;
        final Node next = x.next;// next 
        final Node prev = x.prev; // prev 

        if (prev == null) { // prev == null ,first = next 
            first = next;
        } else { // prev.next = next 
            prev.next = next;
            x.prev = null; // 垃圾回收
        }

        if (next == null) { // next== null ,last = prev 
            last = prev;
        } else { // next.prev = prev 
            next.prev = prev;
            x.next = null; // for GC 
        }

        x.item = null; // for GC 
        size--;
        modCount++;
        return element;
    }

獲取第一個節點值

    /* @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

獲取最後一個節點值

    /**
     * 獲取最後一個節點值
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

刪除第一個節點,並返回其值,可拋出異常

    /**
     * 刪除第一個節點,並返回其值,可拋出異常
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

刪除最後一個節點,並返回節點值,可拋出異常

    /**
     * 刪除最後一個節點,並返回節點值,可拋出異常
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

頭尾插入節點

    /**
     * 第一個位置插入節點
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * 最後一個位置插入節點 
     */
    public void addLast(E e) {
        linkLast(e);
    }

是否包含元素 o

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

獲取元素的個數

    /**
     * 獲取元素的個數
     */
    public int size() {
        return size;
    }

尾部加入節點

    /**
     * 尾部加入節點
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

刪除節點 o

    /**
     * 刪除節點 o 
     * 順序遍歷查找,找到後刪除
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

集合c中元素插入到LinkedList中

    /**
     * 集合c中元素加入的LinkedList中
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection c) {
        return addAll(size, c);
    }

index開始 集合c中元素加入的LinkedList中

    /**
     * index開始 集合c中元素加入的LinkedList中
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection c) {
        checkPositionIndex(index); // 檢查index是否合法 

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node 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;
            Node newNode = new Node<>(pred, e, null);// 新節點 e.prev = pred e.next = 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;
    }

清空

    /**
     * 清空 
     */
    public void clear() {
        //設為null 方便GC
        for (Node x = first; x != null; ) {
            Node next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

獲取index位置的元素

    /**
     * 獲取index位置的元素 
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);// index合法性檢查
        return node(index).item;
    }

index位置元素的值更新

    /**
     * index位置元素的值更新
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        checkElementIndex(index); // index合法性檢查
        Node x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

index位置插入新節點

    /**
     * index位置插入新節點
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

刪除index位置的節點

    /**
     * 刪除index位置的節點
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);// index合法性檢查
        return unlink(node(index));
    }

下標合法性的方法

 /**
     * 是不是下標
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * 是否是合法的插入位置,插入可以查在最後一個節點的後面
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * 越界輸出信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
    /**
    * 檢查index是否合法位置
    */
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    /**
    * 檢查index是否是合法的插入位置
    */
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

返回index位置的節點
通過前後分開查找的方式
平均查找次數應該是:n/2

    /**
     * 返回index位置的節點
     */
    Node node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) { // 查找前一半
            Node x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else { // 查找後一半
            Node x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

獲取節點o第一次出現的下標

   /**
     * 獲取節點o第一次出現的下標
     */
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

獲取節點o最後一次出現的下標

    /**
     * 獲取節點o最後一次出現的下標 
     */
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

隊列的相關操作

    /**
     * 查看隊頂元素
     */
    public E peek() {
        final Node f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 查看隊頂元素 
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E element() {
        return getFirst();
    }

    /**
     * 獲取隊頂元素,並刪除該元素
     * @since 1.5
     */
    public E poll() {
        final Node f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 刪除隊頂元素,並返回該值
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

    /**
     * 隊尾部加入元素
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }

雙端隊列相關操作


    /**
     * 第一個位置插入節點
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * 最後一個位置插入節點
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
     * 查看隊頂元素
     *
     * @return the first element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekFirst() {
        final Node f = first;
        return (f == null) ? null : f.item;
     }

    /**
     * 查看隊尾元素
     * @return the last element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekLast() {
        final Node l = last;
        return (l == null) ? null : l.item;
    }

    /**
     *隊頂元素出隊列
     * @return the first element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollFirst() {
        final Node f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 隊尾元素出隊列
     * @return the last element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollLast() {
        final Node l = last;
        return (l == null) ? null : unlinkLast(l);
    }

棧的相關操作

    /**
     * 入棧
     * @param e the element to push
     * @since 1.6
     */
    public void push(E e) {
        addFirst(e);
    }

    /**
     * 出棧
     * @throws NoSuchElementException if this list is empty
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

刪除元素 o,只刪除第一次出現的那個

    /**
     * 刪除元素 o,只刪除第一次出現的那個
     * @since 1.6
     */
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

刪除元素o,刪除最後一次出現的那個

    /**
     *刪除元素o,刪除最後一次出現的那個
     * @since 1.6
     */
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

返回從index開始的迭代器

   /**
     * 返回從index開始的迭代器
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @see List#listIterator(int)
     */
    public ListIterator listIterator(int index) {
        checkPositionIndex(index);// 下標檢查
        return new ListItr(index);
    }

    private class ListItr implements ListIterator {
        private Node lastReturned = null;
        private Node 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() { // hasNext
            return nextIndex < size;
        }

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

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

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

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

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

        public int nextIndex() { // nextIndex 
            return nextIndex;
        }

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

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

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

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

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

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

後向前的迭代器


    /**
     *後向前的迭代器
     * @since 1.6
     */
    public Iterator descendingIterator() {
        return new DescendingIterator();
    }

    /**
     * 後向前的迭代器
     */
    private class DescendingIterator implements Iterator {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() { // 前驅 
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

獲取LinkedList的clone

    @SuppressWarnings("unchecked")
    private LinkedList superClone() {
        try {
            return (LinkedList) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    /**
     * 獲取的一個clone 
     *
     * @return a shallow copy of this {@code LinkedList} instance
     */
    public Object clone() {
        LinkedList clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Node x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }

轉換成數組

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

LinkedList元素值更新數組a


    /**
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * @throws NullPointerException if the specified array is null
     */
    @SuppressWarnings("unchecked")
    public  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 x = first; x != null; x = x.next)
            result[i++] = x.item;

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

        return a;
    }

序列號

    private static final long serialVersionUID = 876323262645176354L;

輸入輸出流

    /**
     * Saves the state of this {@code LinkedList} instance to a stream
     * (that is, serializes it).
     *
     * @serialData The size of the list (the number of elements it
     *             contains) is emitted (int), followed by all of its
     *             elements (each an Object) in the proper order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Node x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    /**
     * Reconstitutes this {@code LinkedList} instance from a stream
     * (that is, deserializes it).
     */
    @SuppressWarnings("unchecked")
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved