前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LinkedList 源码分析

LinkedList 源码分析

作者头像
Jacob丶
发布2020-08-05 18:07:01
3270
发布2020-08-05 18:07:01
举报
文章被收录于专栏:JacobJacob

简介

LinkedList 底层是一个双向链表。是一个直线型的链表结构。

LinkedList 特点:查询慢,增删快。

结构

LinkedList继承于AbstractSequentialList 实现了List、Deque、Cloneable、java.io.Serializable这些接口。如下:

代码语言:javascript
复制
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  • 继承AbstractSequentialList抽象类:在遍历LinkedList的时候,官方推荐使用迭代器访问。
  • 实现了List接口:提供了相关的添加、删除、修改、遍历等功能。
  • 实现Cloneable:实现clone()方法,实现克隆。
  • 实现java.io.Serializable接口,意味着LinkedList支持序列化,能通过序列化去传输。
  • 实现了Deque接口:提供所有可选的操作。

LinkedList 数据结构

LinkedList 定义了一个私有内部类Node,用来表示链表数据结构,也就是通过Node来存储元素。

代码语言:javascript
复制
    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;
        }
    }

字段

代码语言:javascript
复制
    //集合大小
    transient int size = 0;

    /**
     * Pointer to first node.
     * - 头节点
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     * - 固定式:1.头节点为空,尾节点必然为空;2.头节点中上一个节点为空,元素不为空
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * - 尾节点
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     * - 固定式:1.头节点为空,尾节点必然为空;2.尾节点中下一个节点为空,元素不为空
     */
    transient Node<E> last;

构造方法

LinkedList提供了两种构造方法
LinkedList()

无参构造:构造一个空列表。

代码语言:javascript
复制
    /**
     * Constructs an empty list.
     * - 构造一个空列表。
     */
    public LinkedList() {
    }
LinkedList(Collection<? extends E> c)

构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。

代码语言:javascript
复制
    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     * - 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
     *
     * @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);
    }

    /**
     * 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
     * collection's iterator.  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in
     * progress.  (Note that this will occur if the specified collection is
     * this list, and it's nonempty.)
     * - 将指定集合中的所有元素按照该 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 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
     * 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;

        // pred:指代待添加节点的前一个节点。
        // succ:指代添加节点的位置。
        Node<E> pred, succ;
        // index == size:待添加的元素永远在最后
        // index != size:先获取指定索引对应的Node节点,在把Node节点赋值给Pred
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            // node(index):获取指定索引对应的Node节点
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            //  @SuppressWarnings("unchecked")
            // 告诉编译器忽略 unchecked 警告信息
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            // pred == null:头节点
            // pred != null:非头节点,上一个节点,指向下一个节点
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        // succ == null:表示新添加的元素,是最后一个元素。
        // succ != null:新添加的元素不是最后一个元素。
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }
        // 更新长度
        size += numNew;
        // 修改的次数
        modCount++;
        return true;
    }

    /**
    * - 检查索引是否越界
    */
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

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

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

普通方法

linkFirst(E e)

设置头节点元素

代码语言:javascript
复制
    /**
     * Links e as first element.
     * - 设置头节点元素
     */
    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++;
    }

总结:新建节点赋值给头节点,判断旧头节点是否为空,若为空赋值给尾节点;若不为空把旧头节点的上一个节点指向头节点。

addFirst(E e)

将该元素插入此列表的头部。

代码语言:javascript
复制
    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

总结:内部调用linkFirst()。

linkLast(E e)

设置尾节点元素

代码语言:javascript
复制
    /**
     * 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++;
    }

总结:新建节点赋值给尾节点,判断旧尾节点是否为空,若为空表示该集合为空,没有头节点;若不为空把旧尾节点的下一个节点指向尾节点。

addLast(E e)

将该元素插入到此列表的末尾。

代码语言:javascript
复制
    /**
     * 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()。

linkBefore(E e, Node succ)

在非空节点之前插入元素e。

代码语言:javascript
复制
    /**
     * Inserts element e before non-null Node succ.
     * - 在非空节点之前插入元素e。
     */
    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;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

总结:新建一个节点元素,将上一个节点指向当前节点,将当前旧节点指向新节点。

unlinkFirst(Node f)

删除头节点,并且返回删除的节点的值,使用该方法的前提是参数f是头节点,而且f不能为空。

代码语言:javascript
复制
    /**
     * 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;
    }

总结:头节点置空,把下一节点设置为头节点,若下一节点为空,则尾节点为空。

removeFirst()

删除头节点,并且返回删除的节点的值。

代码语言:javascript
复制
    /**
     * 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);
    }

总结:该方法内部调用unlinkFirst()。

unlinkLast(Node l)

删除尾节点,并且返回删除节点的值。

代码语言:javascript
复制
    /**
     * 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;
    }

总结:尾节点置空,把上一节点设置为尾节点,若上一节点为空,则头节点为空。

removeLast()

删除指定节点,该节点不为空。

代码语言:javascript
复制
   /**
     * 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);
    }

总结:该方法内部调用unlinkLast()。

unlink(Node x)

删除指定节点,该节点不为空。

代码语言:javascript
复制
    /**
     * 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 = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

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

总结:将该节点置空,需要判断是头节点还是尾节点。

getFirst()

获取头节点元素。

代码语言:javascript
复制
    /**
     * 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;
    }

总结:若头节点为空,抛出NoSuchElementException。

getLast()

获取尾节点元素。

代码语言:javascript
复制
    /**
     * 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;
    }

总结:若尾节点为空,抛出NoSuchElementException。

contains(Object o)

判断是否包含某一个元素。

代码语言:javascript
复制
    /**
     * Returns {@code true} if this list contains the specified element.
     * More formally, returns {@code true} if and only if this list contains
     * at least one element {@code e} such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>.
     * - 如果此列表包含指定的元素,则返回true。
     * @param o element whose presence in this list is to be tested
     * @return {@code true} if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) != -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 ? get(i)==null : o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     * - 返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。
     * @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;
    }

总结:循环遍历每个节点,判断是否存在,若存在则返回ture。

lastIndexOf(Object o)

获取指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1。

代码语言:javascript
复制
    /**
     * 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.
     * - 获取指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1。
     * @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;
    }

总结:循环遍历链表,判断元素是否存在。

peek()

检索头节点,但不删除头节点。返回头节点元素。

代码语言:javascript
复制
    /**
     * 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;
    }

其他方法不做阐述,看到这里再看其他方法基本都能看懂。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 结构
  • LinkedList 数据结构
  • 字段
  • 构造方法
    • LinkedList提供了两种构造方法
      • LinkedList()
      • LinkedList(Collection<? extends E> c)
  • 普通方法
    • linkFirst(E e)
      • addFirst(E e)
        • linkLast(E e)
          • addLast(E e)
            • linkBefore(E e, Node succ)
              • unlinkFirst(Node f)
                • removeFirst()
                  • unlinkLast(Node l)
                    • removeLast()
                      • unlink(Node x)
                        • getFirst()
                          • getLast()
                            • contains(Object o)
                              • lastIndexOf(Object o)
                                • peek()
                                相关产品与服务
                                文件存储
                                文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
                                领券
                                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档