1. ホーム
  2. Java

コレクション - LinkedListソースコード解析

2022-02-28 14:44:35

JDKバージョン

JDK 1.8.0_110

参考文献

概要

リンクリスト も実装しています。 リスト インターフェースと Deque インターフェイスを持つため、シーケンシャルコンテナとしてもキューとしても見ることができます ( キュー )、スタック( スタック ).

このように、どうやら LinkedList は万能選手です。スタックやキューを使う必要があるときは リンクドリスト たとえば、Java は公式に スタック というクラスはなく、さらに残念なことに、Javaには キュー クラスがあります(インターフェース名です)。スタックやキューに関して、現在好ましいのは ArrayDeque よりもはるかに優れたインターフェイスを持つ リンクリスト (スタックやキューとして使用する場合)性能が向上します。

リンクリスト は、添え字に関するすべての操作が線形時間であり、先頭や末尾の要素の削除が一定時間だけかかるように実装されています。

効率化のために リンクリスト は同期化されていないので、複数のスレッドで同時にアクセスする必要がある場合は、Collections.synchronizedList() メソッドを使用して最初にラップすることができます。

LinkedListsの実装

基礎となるデータ構造

リンクリスト 底面 双方向リンクリストによる実装 ここでは、要素の挿入・削除時に双方向の連鎖を維持する処理、すなわち リスト インターフェイスを残しながら キュー スタック デク 関連する知識は次節で取り上げる。双方向リンク表の各ノードは、内部クラスである ノード を使って表現します。 リンクされたリスト firstとlastの参照はそれぞれリンクリストの最初と最後の要素を指しています。ダミーは存在しないことに注意してください。リストが空の場合、firstとlastは両方ともnullを指します。

    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     * (first.prev == null && first.item ! = null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     * (last.next == null && last.item ! = null)
     */
    transient Node<E> last;


ここで、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;
        }
    }


コンストラクタ

    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }


getFirst(), getLast()

最初の要素を取得し、最後の要素を取得します。

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

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }


removeFirest()、removeLast()、remove(e)、remove(index)

remove()メソッドにも、指定した要素と等しい最初の要素を削除する remove(Object o)と、指定した添え字の位置にある要素を削除する remove(int index)の2つのバージョンがあります。

要素の削除 - この要素の最初の出現を削除することを意味し、そのような要素がない場合は false を返します。

はequalsメソッドに基づいており、もしそうなら、そのノードは直接アンリンクされる。

LinkedListはNull要素を保持できるので、Null要素の最初の出現を削除することもできる。

    /**
     * Removes the first occurrence of the specified element from this list,
     If this list does not contain the element, it is * unchanged.
     * More formally, removes the element with the lowest index
     * {@code i} such that
     * <tt>(o==null&nbsp;? &nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     Returns {@code true} if this list * contains the specified element (or equivalently, if this list
     * changed as a result of the call).
     *Returns
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    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;
    }
    
    /**
     * Unlinks non-null node x.
     */
    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 element
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {// most

remove(int index) は、添え字カウントを使用して、単にそのインデックスに要素があるかどうかを判断し、もしあれば、ノードのリンクを解除します。

    /**
     * Removes the element at the specified position in this list. shifts any
     * Shifts any subsequent elements to the left (subtracts one from their indices).
     Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list.
     *Returns the element that was removed from the list.
     Returns the element that was removed from the list. * @param index the index of the element to be removed.
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }


head 要素を削除する。

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }


    /**
     * Unlinks non-null first node 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; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size --;
        modCount++;
        return element;
    }


最後の要素を削除します。

	/**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    
    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l ! = null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size --;
        modCount++;
        return element;
    }




追加()

追加() メソッドには2つのバージョンがあり、1つは  add(E e), the このメソッドは LinkedList は、リストの最後を指すlastを持ち、最後に要素を挿入するのに一定の時間がかかるからです。もうひとつのメソッドは add(int index, E element) で、これは指定された添え字に要素を挿入し、正確な位置を見つけるために線形ルックアップが必要で、その後、参照を修正して挿入を完了させます。

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    
    /**
     * Links e as last element.
     */
    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++;
    }


<イグ

add(int index, E element) は index==size のとき add(E e) と等価である。 

そうでない場合は、2つのステップで.

  1. まず、インデックスに基づいて挿入する位置を見つけます。つまり、node(index) メソッドです。
  2. 参照を修正して、挿入操作を完了します。
    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * Subsequent elements to the right (ads one to their indices).
     * @param index
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

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


上のコードの node(int index) 関数にはちょっとした仕掛けがあります。連鎖は双方向なので、index < (size >> 1) という条件によって、先頭から後ろ、または最後から前に検索できます。つまり、インデックスが前寄りか後ろか、ということです。ここでわかるように、linkedListはarrayListほどインデックスによる要素の取得が効率的ではありません。

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    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;
        }
    }


addAll()

addAll(index, c) は add(index,e) の直接の呼び出しとしては実装されていません。これは主に効率の問題と fail-fast の modCount が 1 回だけ増加するためです。

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * The behavior of this operation is undefined if
     The behavior of this operation is undefined if * the specified collection is modified while the operation is in
     * (Note that this will occur if the specified collection is
     (Note that this will occur if the specified collection is * this list, and it's nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * Shifts the element
     Shifts the element * currently at that position (if any) and any subsequent elements to
     Shifts the element * currently at that position (if any) and any subsequent elements to * the right (initializes their indices).  The new elements will appear
     The new elements will appear * in the list in the order that they are returned by the
     The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator.
     The new elements will appear * in the list in the order that they are returned by the specified collection's iterator.
     * @param index index at which to insert the first element
     * from the specified collection
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    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) {
            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 = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }


クリア()

GCが配置された要素をより速く取得するために、ノード間の参照関係をNULLにする必要があります。

    /**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    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++;
    }


位置決めアクセス方式

インデックスによる要素の取得

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }



ある位置の要素を再割り当てする。

    /**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }


指定されたインデックスの位置に要素を挿入する。

    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * Subsequent elements to the right (ads one to their indices).
     * @param index
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

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


指定された位置の要素を削除します。

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their indices).
     Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list.
     *Returns the element that was removed from the list.
     Returns the element that was removed from the list. * @param index the index of the element to be removed.
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }


その他の場所に対応するメソッド。



    /**
     * Tells if the argument is the index of an existing element.
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */private
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }


検索操作

ルックアップ操作の本質は、要素の添え字を見つけることである。

最初に出現するインデックスを探し、見つからなければ-1を返す。

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index {@code i} such that
     * <tt>(o==null&nbsp;? &nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the first occurrence of the specified element in
     * this list, or -1 if this list does not contain the element
     */
    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;
    }


indexの最後の出現箇所を検索し、見つからなければ-1を返す。


    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index {@code i} such that
     * <tt>(o==null&nbsp;? &nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the last occurrence of the specified element in
     * this list, or -1 if this list does not contain the element
     */
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x ! = null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x ! = null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }


キューメソッド

   
    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E element() {
        return getFirst();
    }

    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

    /**
     * Adds the specified element as the tail (last element) of this list.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }


Dequeメソッド

    /**
     * Inserts the specified element at the front of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerFirst})
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * Inserts the specified element at the end of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerLast})
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
     * Retrieves, but does not remove, the first element of this list,
     * or returns {@code null} if this list is empty.
     * @return
     * @return the first element of this list, or {@code null}
     * if this list is empty
     * @since 1.6
     */
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

    /**
     * Retrieves, but does not remove, the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the last element of this list, or {@code null}
     * if this list is empty
     * @since 1.6
     */
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    /**
     * Retrieves and removes the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the first element of this list, or {@code null} if
     * this list is empty
     * @since 1.6
     */
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * Retrieves and removes the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the last element of this list, or {@code null} if
     * this list is empty
     * @since 1.6
     */
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    /**
     * Pushes an element onto the stack represented by this list. In other
     * words, inserts the element at the front of this list.
     In other * words, inserts the element at the front of this list.
     * <p>This method is equivalent to {@link #addFirst}.
     * @param e the element to this list.
     * @param e the element to push
     * @since 1.6
     */
    public void push(E e) {
        addFirst(e);
    }

    /*
     * Pops an element from the stack represented by this list. In other
     * In other words, removes and returns the first element of this list.
     *In other words, removes and returns the first element of this list.
     * <p>This method is equivalent to {@link #removeFirst()}.
     *
     * @return the element at the front of this list (which is the top
     * of the stack represented by this list)
     * @throws NoSuchElementException if this list is empty
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

    /**
     * Removes the first occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     If the list * does not contain the element, it is unchanged.
     If the list * does not contain the element, it is unchanged.
     * @param o element to be removed from this list, if present
     * @return {@code true} if the list contained the specified element
     * @since 1.6
     */
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    /**
     * Removes the last occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     If the list * does not contain the element, it is unchanged.
     If the list * does not contain the element, it is unchanged.
     * @param o element to be removed from this list, if present
     * @return {@code true} if the list contained the specified element
     * @since 1.6
     */
    public boolean removeLastOccurrence(Object o) {
        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)) {