首页 > 编程语言 >LinkedList【源码解析】

LinkedList【源码解析】

时间:2024-07-22 15:44:20浏览次数:10  
标签:Node index 解析 LinkedList element next 源码 null first

show Diagram

按照上图的内容来看,LinkedList实现了CloneableSerializable两个接口,并继承了AbstractSequentialList类。

LinkedList底层实现了双向链表。以下是LinkedList源码。

内部结构

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    protected transient int modCount = 0; // 解决fail-fast

    transient int size = 0; //数据个数

    /**
     * 指向双向链表头节点
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * 指向双向链表尾节点
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

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

protected transient int modCount = 0;
       记录对 List 操作的次数,主要使用是在 Iterator,是防止在迭代的过程中集合被修改。该变量定义在AbstractList中,被ArrayList继承。思考一下,如果我们在遍历集合时,对集合进行了修改,比如说删除了某一个元素,那么很容易导致结果出错或者下标越界。

       每个节点(Node对象)中维护了 prevnextitem 3 个属性,注意 以下内容是LinkedList中的一个静态内部类。

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

构造函数

       LinkedList 有两个构造函数,其中一个为空构造,另一个则可传入集合。可以发现,传入集合的构造方法其实是先调用空构造,然后使用 addAll 方法将集合的数据添加进链表中。

元素添加

add(E 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;
    }

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

将最后一个节点last添加到新的节点的prev,创建新节点,将新节点赋值到last变量中。若这是第一个插入的元素(l = last = null),那该节点是尾节点也是头节点。

add(int index, E element)

指定位置,插入元素。

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

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

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

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

    /**
     * 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;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

       该方法首先检查数组插入位置是否越界,若越界则抛出异常。判断插入的位置是否是尾部,如果是尾部直接调用 linkLast 方法,若不是则调用linkBefore 方法。

解释:该方法是找到插入位置的元素。可以很清楚的看到,该方法对index 进行了比较,如果小于 size 的一半(size >> 1 右移一位,相当于除2),那么是从头往后查找元素,否则从尾部往前查找元素。然后返回这个元素。

解释:插入数据到找到的元素的前一个位置。这里还是得判断 pred 是否为空,如果为空,那么插入的位置就是第一个位置。

addFirst(E e) 和 addLast(E e)

addFirst 插入头部,addLast 插入尾部

addAll(int index, Collection<? extends E> 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;

        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;
    }
  1. 判断插入位置是否越界。判断插入集合长度是否为0。

  2. 循环插入节点

  3. 插入之后将节点连接

元素删除

removeFirst()

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

remove()

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

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

remove(Object o)

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  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
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @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 = 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;
    }

unlink() 特殊处理头尾节点,其他节点正常。

remove(int index)

    /**
     * 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);
        return unlink(node(index));
    }

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

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

标签:Node,index,解析,LinkedList,element,next,源码,null,first
From: https://www.cnblogs.com/dragon-925/p/18315204

相关文章

  • 使用 TextFSM 解析 CISCO 的 con/aux/vty 配置
    我正在尝试使用TextFSM从Cisco路由器解析控制台(con/aux/vty)的配置,特别是命令showrunning-config|的输出。部分线。出现此问题的原因是,这部分配置并未像往常一样以“!”结束“linevtys”,这会在尝试检测记录的结尾而不错过该行作为下一条记录的开头时出现问题。我......
  • “点点通”餐饮点餐小程序-计算机毕业设计源码11264
    "点点通"餐饮点餐小程序XXX专业XX级XX班:XXX   指导教师:XXX摘要 随着中国经济的飞速增长,消费者的智能化水平不断提高,许多智能手机和相关的软件正在得到更多的关注和支持。其中,微信的餐饮点餐小程序更是深得消费者的喜爱,它的出现极大地改善了消费者的生活质量,同时,它还创......
  • SSM泰华超市商品管理系统-计算机毕业设计源码11946
    目 录摘要1绪论1.1研究背景1.2 研究意义1.3论文结构与章节安排2系统分析2.1可行性分析2.2系统流程分析2.2.1数据新增流程3.2.2 数据删除流程2.3 系统功能分析2.3.1功能性分析2.3.2非功能性分析2.4 系统用例分析2.5本章小结3 系......
  • SSM小说阅读网站-计算机毕业设计源码11362
    摘 要本文介绍了一个基于SSM框架和MySQL数据库的小说阅读网站的设计与实现。该网站旨在为用户提供一个方便、舒适的在线小说阅读平台。该小说阅读网站具有以下主要功能:用户注册与登录、小说分类浏览、小说搜索、阅读历史记录、小说畅听等。通过该网站,用户可以根据自己的兴......
  • HTTP协议解析
    HTTP协议解析详解HTTP(HyperTextTransferProtocol,超文本传输协议)是互联网上应用最为广泛的一种网络协议。它是客户端和服务器之间进行请求和响应的标准协议。理解HTTP协议的解析过程对于开发WEB应用至关重要,因为它定义了客户端和服务器如何进行通信。1.HTTP协议的基本概......
  • Java计算机毕业设计旅行分享平台(开题报告+源码+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景在数字化时代,旅游行业正经历着前所未有的变革。随着人们生活水平的提高和休闲方式的多样化,旅行已成为现代人追求生活品质、拓宽视野的重要方式之一。......
  • Java计算机毕业设计旅游网站的设计与实现(开题报告+源码+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着互联网的普及和人们生活水平的提高,旅游已成为现代人休闲娱乐的重要方式之一。然而,面对繁多的旅游信息、复杂的行程规划与预订流程,传统的旅游服务......
  • Java计算机毕业设计健美操社团活动信息管理系统设计与实现(开题报告+源码+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景在当今高校校园文化日益丰富的背景下,健美操社团作为促进学生身心健康、增强团队协作能力的重要平台,其活动组织与管理效率直接影响到社团的活力与影响......
  • Java计算机毕业设计健身场馆预约(开题报告+源码+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着人们对健康生活的日益重视,健身已成为现代都市人不可或缺的生活方式之一。然而,传统健身场馆在管理和服务上常面临诸多挑战,如会员管理混乱、场地资......
  • SpringBoot原理解析(二)- Spring Bean的生命周期以及后处理器和回调接口
    SpringBoot原理解析(二)-SpringBean的生命周期以及后处理器和回调接口文章目录SpringBoot原理解析(二)-SpringBean的生命周期以及后处理器和回调接口1.Bean的实例化阶段1.1.Bean实例化的基本流程1.2.Bean实例化图例1.3.实例化阶段的后处理器1.3.1.实例化阶段后处理器......