Collection-LinkedList源码解析

news2024/10/12 7:46:33

文章目录

    • 概述
    • LinkedList实现
      • 底层数据结构
      • 构造函数
      • getFirst(), getLast()
      • removeFirst(), removeLast(), remove(e), remove(index)
      • add()
      • addAll()
      • clear()
      • Positional Access 方法
      • 查找操作

概述

LinkedList同时实现了List接口和Deque接口,也就是说它既可以看作一个顺序容器,又可以看作一个队列(Queue),同时又可以看作一个栈(Stack)。这样看来,LinkedList简直就是个全能冠军。当你需要使用栈或者队列时,可以考虑使用LinkedList,一方面是因为Java官方已经声明不建议使用Stack类,更遗憾的是,Java里根本没有一个叫做Queue的类(它是个接口名字)。关于栈或队列,现在的首选是ArrayDeque,它有着比LinkedList(当作栈或队列使用时)有着更好的性能。


LinkedList_base

LinkedList实现

底层数据结构

LinkedList底层通过双向链表实现,本节将着重讲解插入和删除元素时双向链表的维护过程。双向链表的每个节点用内部类Node表示。LinkedList通过firstlast引用分别指向链表的第一个和最后一个元素。当链表为空的时候firstlast都指向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;
    }

removeFirst(), removeLast(), remove(e), remove(index)

remove()方法也有两个版本,一个是删除跟指定元素相等的第一个元素remove(Object o),另一个是删除指定下标处的元素remove(int index)


LinkedList_remove.png

删除元素 - 指的是删除第一次出现的这个元素, 如果没有这个元素,则返回false;判断的依据是equals方法, 如果equals,则直接unlink这个node;由于LinkedList可存放null元素,故也可以删除第一次出现null的元素;

    /**
     * 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; // GC
        size--;
        modCount++;
        return element;
    }

remove(int index)使用的是下标计数, 只需要判断该index是否有元素即可,如果有则直接unlink这个node。

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

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

删除last元素:

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

add()

add()*方法有两个版本,一个是add(E e),该方法在*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++;
    }

LinkedList_add

add(int index, E element), 当index==size时,等同于add(E e); 如果不是,则分两步: 1.先根据index找到要插入的位置,即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 (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));
    }

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
     * 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.)
     *
     * @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;

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

clear()

为了让GC更快可以回收放置的元素,需要将node之间的引用关系赋空。

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

Positional Access 方法

通过index获取元素

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

将元素插入到指定index位置:

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

删除指定位置的元素:

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

查找操作

查找操作的本质是查找元素的下标:

查找第一次出现的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;
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2207440.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【LeetCode】修炼之路-0005-Longest Palindromic Substring【python】

题目 Given a string s, return the longest palindromic substring in s. Example 1: Input: s “babad” Output: “bab” Explanation: “aba” is also a valid answer. Example 2: Input: s “cbbd” Output: “bb” 前言 首先&#xff0c;题目我们就看不懂 &…

Android JNI调用.c文件

Android JNI调用.c文件 1.创建Android项目,创建一个jni目录来存放.c代码 2.CMakeLists.txt cmake_minimum_required(VERSION 3.10.2) project("MyApplication")add_library(native-lib SHARED native-lib.c)find_library(log-lib log)target_link_libraries

C++初阶--类与对象(上)

一、面向对象&#xff08;OOP&#xff09;and 面向过程&#xff08;POP&#xff09; 1.面向过程&#xff08;POP&#xff09; 面向过程&#xff1a;就像做一道家常菜 想象一下&#xff0c;你要做一道简单的家常菜&#xff0c;比如番茄炒蛋。面向过程的方式就像是这样&#x…

单片机教案 2.2 ATmega2560单片机闪烁灯的制作和编程

2.1 单片机教案 2.1 ATmega2560单片机最小应用系统-CSDN博客 2.2 ATmega2560单片机闪烁灯的制作和arduino编程 ATmega2560单片机闪烁灯的制作和Arduino编程是一个经典的嵌入式系统设计案例。以下将分别介绍使用ATmega2560单片机直接编程和使用Arduino平台&#xff08;基于ATm…

[已解决]DockerTarBuilder永久解决镜像docker拉取异常问题

前阵子发现阿里云的docker加速镜像失效了&#xff08;甚至连nginx都拉取不了&#xff09;&#xff0c;重新换了并且加多了网络上比较常用的dokcer加速源&#xff0c;可以解决一部分问题&#xff0c;但仍然有一些镜像的某个版本或一些比较冷的镜像就是拉取不了&#xff0c;原因未…

分组相关 -- VPLS

VPLS&#xff08;Virtual Private LAN Service&#xff0c;虚拟专用局域网服务&#xff09;是IETF定义的以太网多点到多点业务模型&#xff0c;其通过MPLS-TP网络连接地域上相互隔离的多个LAN网络&#xff0c;为用户提供MP2MP和P2MP业务。 业务模型 VPLS是以MPLS技术实现传送…

Java创建型模式(二)——工厂模式(简单工厂模式、工厂方法模式、抽象工厂模式、工厂模式扩展等完整详解,附有代码——案例)

文章目录 五.工厂模式5.1 概述5.2简单工厂模式5.2.1 概述5.2.2 结构5.2.3 实现5.2.4 优缺点5.2.5 扩展—静态工厂 5.3 工厂方法模式5.3.1概述5.3.2 结构5.3.3 实现5.3.4 优缺点 5.4 抽象工厂模式5.4.1 概述5.4.2 结构5.4.3 实现5.4.4 优缺点5.4.5 使用场景 5.5 工厂模式扩展 五…

基于YOLO11/v10/v8/v5深度学习的安检X光危险品检测与识别系统设计与实现【python源码+Pyqt5界面+数据集+训练代码】

《博主简介》 小伙伴们好&#xff0c;我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。 ✌更多学习资源&#xff0c;可关注公-仲-hao:【阿旭算法与机器学习】&#xff0c;共同学习交流~ &#x1f44d;感谢小伙伴们点赞、关注&#xff01; 《------往期经典推…

深度学习之常用数据集下载

在复现他人代码的过程中&#xff0c;有时需要下载数据集&#xff0c;才可跑通模型&#xff0c;但部分数据集在网上难以收集或是通过翻墙的手段才可获取。于是&#xff0c;在此总结了一些数据集的收集。 1、方法一&#xff1a;Kaggle官网下载 之前有推荐kaggle(Kaggle官网网址…

每日论文19-10GHz处相噪能达到-138dBc/Hz@1MHz串联谐振VCO

《Series-Resonance BiCMOS VCO with Phase Noise of -138dBc/Hz at 1MHz Offset from 10GHz and -190dBc/Hz FoM 》2022ISSCC 不用并联谐振了&#xff0c;用串联谐振&#xff0c;能在相噪性能上获得更极端地提升。 假设有源电路的噪声因子F相同&#xff0c;LC-tank的质量因子…

QD1-P17 HTML 下拉框标签(select、option)

本节学习 HTML 常用标签&#xff1a;select和option ‍ 本节视频 www.bilibili.com/video/BV1n64y1U7oj?p17 ‍ 知识点1&#xff1a;select标签用法 演示 ​​ HTML <select name"city"><option>北京</option><option>上海</opti…

【STM32CubeMX开发】-1-GPIO:点亮一个LED,以及按键KEY的捕获

案例背景&#xff1a; 我们将实现这样一个效果&#xff1a;按下按键KEY&#xff0c;点亮LED灯&#xff1b;松开按键KEY&#xff0c;熄灭LED灯。 KEY需配置为上拉输入&#xff1b;LED需配置为推挽输出。 目录 1 STM32CubeMX中配置 – GPIO 1.1 PIN引脚配置 1.2 GPIO配置 1…

三款GIS工具多角度对比:免费的倾斜摄影OSGB/3Dtiles编辑转换发布平台

GIS数据处理工具在现代技术与应用中扮演着至关重要的角色&#xff0c;它们不仅是连接原始地理信息与可分析、可视化数据的桥梁&#xff0c;更是推动地理信息系统&#xff08;GIS&#xff09;在各个行业领域深入发展与应用不可或缺的关键工具。选择一款合适的工具直接关系到数据…

电汽车充电革命:充电桩的过去现在与未来

电动汽车充电革命&#xff1a;中国充电桩行业的过去、现在与未来 一、发展历程概述 中国充电桩行业的发展历程可划分为以下几个阶段&#xff1a; 1. 初始期&#xff08;2006-2008年&#xff09;&#xff1a;在此阶段&#xff0c;国家队主导市场&#xff0c;主要参与者包括国…

《智慧博物馆:科技与文化的完美融合》

《智慧博物馆&#xff1a;科技与文化的完美融合》 一、智慧博物馆的兴起与发展 随着科技的飞速发展&#xff0c;智慧博物馆应运而生。进入新时代&#xff0c;大数据、人工智能、信息化的进步以及智能产品的应用&#xff0c;改变了人们接收信息和学习的习惯。为顺应社会变革&am…

alter system reset scope sid不要随便加 查询视图

全局变量 写全比较稳妥 set的时候自动加both &#xff0c; reset时不是自动both Applies to: Oracle Database - Enterprise Edition - Version 11.2.0.4 and later Information in this document applies to any platform. Symptoms When the OPTIMIZER_FEATURES_ENABLE p…

Apifox「动态值」全新升级:灵活mock类型的数据

在使用 Apifox 进行接口测试时&#xff0c;你可能不希望将接口参数的值固定&#xff0c;也不想每次发送请求时手动修改数据&#xff0c;而是希望参数值能够自动变化&#xff0c;并且这个参数值能够符合真实场景中的数据需求。比如&#xff0c;你可能需要随机生成数字、字符串、…

90、Python之鸭子类型:for循环的本质,进一步解析迭代协议

引言 在前面的文章中&#xff0c;我们简单介绍了Python中的可迭代对象、迭代器、以及迭代协议的概念。今天就for这个用得特别多&#xff0c;觉得很熟悉很简单的语法结构&#xff0c;稍微展开一下&#xff0c;从而更好地加深对迭代协议的理解。 本文的主要内容有&#xff1a; …

<<迷雾>> 第11章 全自动加法计算机(1)--比特单元 示例电路

具有唯一输入/输出线的存储器 info::操作说明 读取时, 将 读R 开关闭合即可, Q 的输出将通过传输门 G 到达输出 DB 处 写入时, 首先将 写W 开关闭合, 再将上方为测试引入的开关闭合, 此时此高电平将写入 Q 之后断开 写W 的开关, 写入状态结束, 之后可将上方为测试引入的开关断开…

使用MySQL API 进行多线程数据库增删改查操作

使用MySQL API 进行多线程数据库增删改查操作 准备工作安装MySQL Connector/C包含必要的头文件初始化MySQL连接增删改查处理插入数据删除数据更新数据查询数据主函数注意事项在现代的应用程序中,数据库操作往往是性能的关键瓶颈之一。为了提高数据库操作的效率,多线程技术被广…