欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LinkedList源码解析——基于JDK1.8

程序员文章站 2022-06-04 19:26:42
...

1 前言

1.1 常量

	//链表的长度
	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;

1.2 类

	//通过Node构建list,本质是双向链表
	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;
        }
    }

2 方法解析

2.1 构造方法

	/**
     * Constructs an empty list.
     */
    public LinkedList() {
    }
	/**
	 * 根据指定的Collection构建list
     * 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);
    }

2.2 常用方法

2.2.1 add(E)
	/**
	 * 添加指定的元素到链表末尾
     * 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;
    }

linkLast

	/**
	 * 将e作为最后一个元素加入链表
     * Links e as last element.
     */
    void linkLast(E e) {
        //保存当前最后的结点
        final Node<E> l = last;
        //l:上一个结点
        //e:添加的e
        //null:下一个结点为空
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        //如果是空链表第一次添加
        //尾结点即为头结点
        if (l == null)
            first = newNode;
        //否则,将上一个结点指向尾结点
        else
            l.next = newNode;
        size++;
        modCount++;
    }
2.2.2 add(int,E)
	/**
	 * 插入指定的元素到特定的位置
     * 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 (adds one to their indices).
     *
     * @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);

        //如果index==size,插入末尾
        if (index == size)
            linkLast(element);
        //否则,在指定下标之前插入(插入后,下标变成指定下标)
        else
            linkBefore(element, node(index));
    }

linkBefore

	/**
	 * 在非空结点succ前插入结点
     * Inserts element e before non-null Node succ.
     */
    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);
        succ.prev = newNode;
        //如果插入结点的前一个结点为空,则插入结点为头结点。改变first指向
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
2.2.3 addFirst(E)
	/**
	 * 将指定的元素插入此列表的开头
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

linkFirst

	/**
     * Links e as first element.
     */
    private void linkFirst(E e) {
        //首先找到指向头结点的first
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        //改变first
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
2.2.4 addLast(E e)
	/**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

linkLast

	/**
     * 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++;
    }
2.2.5 addAll(Collection<? extends E> )
	public boolean addAll(Collection<? extends E> c) {
        //size:添加开始的地方
        return addAll(size, c);
    }

addAll(int, Collection<? extends E> )

	/**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  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;
            //前继为last(最后一个结点)
            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;
    }

node(int)

	/**
	 * 返回在指定下标的非空结点
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);

        //看index是否小与size的一半,从前面遍历寻找,否则从最后开始
        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.2.6 remove(int)
	/**
	 * 移除对应下标的元素
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * 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);
        //node(index),找到对应的结点
        return unlink(node(index));
    }

unlink

	/**
     * 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;

        //如果删除的是头结点,改变first
        if (prev == null) {
            first = next;
        } else {
            //否则,删除结点的上一个结点指向删除结点的下一个结点
            prev.next = next;
            //将删除结点指向上一个结点的记录清空
            x.prev = null;
        }

        //如果删除的是尾结点,改变last
        if (next == null) {
            last = prev;
        } else {
            //否则,删除结点的下一个结点指向上一个结点的记录改变
            next.prev = prev;
            //与上相同
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
2.2.7 remove(Object)
	public boolean remove(Object o) {
        //如果o为null
        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;
    }
2.2.8 set(int, E)
	/**
	 * 将list中指定位置的元素替换为指定元素
     * 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;
    }
2.2.9 get(int)
 	/**
     * 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);
        //先通过node()函数找到相应的结点,再返回item
        return node(index).item;
    }
2.2.10 clear()
	/**
	 * 清除所有的元素
     * 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++;
    }
2.2.11 listIterator(int)
	public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

ListItr

	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.next;
            //下标+1
            nextIndex++;
            return lastReturned.item;
        }

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

        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();
			//在size==index时,next==null,上一个结点是最后一个结点
            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);
            //如果是在previous中调用
            if (next == lastReturned)
                next = lastNext;
            else
            //如果是在next中调用
                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();
        }
    }
2.2.12 descendingIterator()
	public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

DescendingIterator

	/**
	 * 适配器通过ListItr.previous提供下行迭代器(倒转,从最后的结点开始)
     * Adapter to provide descending iterators via ListItr.previous
     */
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }
相关标签: Java 源码