LinkedList源码

LinkedList由双向链表实现,实现了List、Deque、Serializable、Cloneable接口,能被克隆和实例化。

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

1.存储结构Node

包含了三个字段,item为数据项,next为当前节点的下一个节点,prev为当前节点的前一个节点。

    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.字段

成员变量也比较简单,包含了一个头结点和尾节点,size是链表中节点的个数。

    /**
     * 链表中节点的个数
     */
    transient int size = 0;

    /**
     * 头结点
     */
    transient Node<E> first;

    /**
     * 尾节点
     */
    transient Node<E> last;

3.构造函数

 /**
     * 构造函数,什么也不做
     */
    public LinkedList() {
    }

    /**
     * 创建一个包含集合中元素的链表
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

4.添加方法

  添加节点可以使用头插法也可以使用尾插法,默认使用尾插法添加新节点。

  /**
     * 在头结点添加节点
     */
    private void linkFirst(E e) {
        //记录当前的头节点
        final Node<E> f = first;
        //创建一个新节点,next指向头节点,prev为null
        final Node<E> newNode = new Node<>(null, e, f);
        //将newNode设为头节点
        first = newNode;
        //如果原来的头结点为空
        if (f == null)
            //将尾节点设为newNode,由于只有一个节点,newNode既是头结点又是尾节点
            last = newNode;
        else
            //将原来的头结点的prev指向新创建的节点
            f.prev = newNode;
        //更新大小
        size++;
        modCount++;
    }

    /**
     * 从尾部添加节点
     */
    void linkLast(E e) {
        //先保存尾节点
        final Node<E> l = last;
        //创建一个prev指向尾节点,next指向空的节点
        final Node<E> newNode = new Node<>(l, e, null);
        //将新节点设为尾节点
        last = newNode;
        //如果原来的链表是空链表
        if (l == null)
            //新节点也是头结点
            first = newNode;
        else
            //将原来尾节点的next指向新节点
            l.next = newNode;
        size++;
        modCount++;
    }

    /**
     * 在succ之前插入非空节点
     */
    void linkBefore(E e, Node<E> succ) {
        // 获取succ的前一个节点
        final Node<E> pred = succ.prev;
        //创建新节点,prev指向succ的前一个节点,next指向succ
        final Node<E> newNode = new Node<>(pred, e, succ);
        //将succ的prev执行新创建的节点
        succ.prev = newNode;
        //如果succ是头结点
        if (pred == null)
            //将新创建的节点设为头结点
            first = newNode;
        else
            //更新pred的next,将它指向新创建的节点
            pred.next = newNode;
        size++;
        modCount++;
    }

 /**
     * 在首部添加节点
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * 在尾部添加节点
     */
    public void addLast(E e) {
        linkLast(e);
    }

/**
     * 添加节点,默认在尾部添加
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

 /**
     * 将集合中的元素添加到链表
     */
    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;
        //pred要插入位置的前一个节点,succ为需要插入节点的位置
        Node<E> pred, succ;
        //如果要插入位置等于链表的大小,说明需要在尾节点后面添加
        if (index == size) {
            succ = null;
            //pred指向要插入位置的前一个节点也就是尾节点
            pred = last;
        } else {//如果不在尾部添加
            //寻找index位置的节点
            succ = node(index);
            //index位置的前一个节点
            pred = succ.prev;
        }
        //遍历数组
        for (Object o : a) {
            //
            @SuppressWarnings("unchecked") E e = (E) o;
            //创建新节点,prev指向pred
            Node<E> newNode = new Node<>(pred, e, null);
            // 如果要插入位置的前一个节点是空,说明要插入位置是头结点
            if (pred == null)
                first = newNode;
            else
                //将要插入位置的前一个节点的next指向新创建的节点
                pred.next = newNode;
            //将pred指向当前节点
            pred = newNode;
        }
        //如果要插入位置为null
        if (succ == null) {
            //将新插入的最后一个节点设为尾节点
            last = pred;
        } else {
            //将新插入的最后一个节点的next指向原链表要插入位置的节点
            pred.next = succ;
            succ.prev = pred;
        }

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

 /**
     * 在指定位置添加节点
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            //在尾部添加
            linkLast(element);
        else
            //找到index处的节点,然后在该节点前添加新节点
            linkBefore(element, node(index));
    }

5.获取和查找

(1)LinkedList提供了正向查找和反向查找两种方法,需要对整个链表进行遍历,如果找到返回对象在链表中的位置。

(2)如果根据索引查找,LinkedList会根据链表中节点的个数/2算出中间位置的索引,然后比较,如果大于中间位置的索引,从中间索引之后开始查找,否则反之。

 /**
     * 获取头结点
     */
    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;
    }

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

 /**
     * 根据位置获取节点
     */
    public E get(int index) {
        //检查位置是否合法
        checkElementIndex(index);
        return node(index).item;
    }


    /**
     * 根据位置找到相应的节点
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
        // 计算链表的中心节点,如果index在中部之前,从头结点向后数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;
        }
    }

    // Search Operations

    /**
     * 正向查找节点,如果找到返回节点的位置
     */
    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;
    }

    /**
     * 反向查找节点
     */
    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;
    }

6.删除

(1)从remove方法中可以看出如果删除的节点是null的话是单独进行处理的,LinkedList是允许null值插入的。

(2)删除节点时同样需要遍历链表,寻找要删除的节点,然后删除。

    /**
     * 删除节点
     */
    public boolean remove(Object o) {
        //如果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;
    }

  /**
     * 清空链表
     */
    public void clear() {
        //遍历节点
        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++;
    }

  /**
     * 删除节点
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

7.更新

    /**
     * 更新节点的值
     */
    public E set(int index, E element) {
        checkElementIndex(index);
        //根据位置找到该节点
        Node<E> x = node(index);
        E oldVal = x.item;
        //更新节点的值
        x.item = element;
        return oldVal;
    }

8.Queue操作和Dequeue操作

由于LinkedList实现了Queue接口,可以使用LinkedList模拟队列和双端队列,因此提供了一些队列的操作方法。

 /**
     * 返回头结点的数据,如果此队列为空,则返回 null
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 获取但不移除此队列的头;如果此队列为空,则抛出NoSuchElementException异常
     */
    public E element() {
        return getFirst();
    }

    /**
     * 获取并移除此队列的头,如果此队列为空,则返回 null
     * @return
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 获取并移除此队列的头,如果此队列为空,则抛出NoSuchElementException异常
     * @return
     */
    public E remove() {
        return removeFirst();
    }

    /**
     * 将指定的元素插入队列,从尾部插入
     * @param e
     * @return
     */
    public boolean offer(E e) {
        return add(e);
    }

双端队列操作:

  /**
     * 将指定的元素插入队列,从头部插入
     * @param e
     * @return
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * 将指定的元素插入此双端队列的末尾
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
     * 获取但不移除此双端队列的第一个节点;如果此双端队列为空,则返回 null
     */
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 获取但不移除双端队列的最后一个节点,如果为空返回null
     */
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    /**
     * 获取并移除队列的第一个节点
     * @since 1.6
     */
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 获取并移除队列的最后一个节点
     */
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    /**
     * 队列中添加节点,从头部添加
     */
    public void push(E e) {
        addFirst(e);
    }

    /**
     * 弹出/删除节点,从头部删除
     */
    public E pop() {
        return removeFirst();
    }

    /**
     * 从此双端队列移除第一次出现的指定元素,如果列表中不包含次元素,则没有任何改变
     */
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    /**
     * 从此双端队列移除最后一次出现的指定元素,如果列表中不包含次元素,则没有任何改变
     */
    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)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

9.其他方法

  private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * 检验位置是否合法(大于等于0小于等于节点的个数)
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * 错误信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 检查索引是否合法
     * @param index
     */
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 检查位置是否合法
     * @param index
     */
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 链表的大小
     */
    public int size() {
        return size;
    }

    /**
     * 克隆方法
     */
    public Object clone() {
        LinkedList<E> 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<E> 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<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

    /**
     * 转为数组
     */
    @SuppressWarnings("unchecked")
    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;
    }

    private static final long serialVersionUID = 876323262645176354L;

    /**
     * 序列化
     */
    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<E> x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    /**
     * 反序列化
     */
    @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)LinkedList基于双向链表实现,插入删除效率高,同时也可以作为栈、队列、双端队列来使用。

(2)LinkedList是非线程安全的。

(3)LinkedList中的元素可以为null。

(4)实现了Serializable、Cloneable接口能被克隆和实例化。

参考:

jdk1.8.0_45源码解读——LinkedList的实现


【Java集合源码剖析】LinkedList源码剖析


猜你喜欢

转载自blog.csdn.net/lom9357bye/article/details/79845411