常用集合之LinkedList源码浅析

LinkedList 集合常用方法 Linked List 是 java.util 包中 Collection 框架的一部分。 > LinkedList 数据结构的实现,它是一种线性数据结构,其中元素不存储在连续位置,每个元素都是一个单独的对象,具有数据部分和地址部分。 > 元素使用指针和地址链接。每个元素称为一个节点 阅读详情

上一篇 【ArrayList和Vector源码解刨对比】

先看 LinkedList 部分源码:


public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    //链表大小
    transient int size = 0;
    //首节点
    transient Node<E> first;
    //尾节点
    transient Node<E> last;

    //添加一个元素 ,默认是添加到链表的尾部
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //添加到链表的尾部
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)//如果尾节点为null,表示链表为空,首节点为第一个添加的节点
            first = newNode;
        else
            l.next = newNode; //和新添加的节点连接起来
        size++;
        modCount++;
    }
}

我们来看看Node,Node是LinkedList的内部类,源码如下,类似C++中的结构体:

 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实际上就是一个 双向链表 如下图:

由此,链表添加数据较ArrayList快,由上篇文章分析可知,ArrayList的添加数据最终是调用底层C++或是C的代码,这是一个耗时操作。而LinkedList采用特殊的数据结构链表的形式,插入就相对简单快速。相反,LinkedList查询效率就不敌ArrayList了。

ps: 文末推荐其他几篇有关集合的文章:

从源码分析LinkedList集合 从源码分析LinkedList集合简介构造方法LinkedList()LinkedList(Collection<? extends E> c)常用方法int size()E getFirst()E getLast()E removeFirst()E removeLast()void addFirst(E e)void addLast(E e)boolean contains(Object o)int indexOf(Object o)int lastIndexOf(Object o)向列表中添 阅读详情

相关推荐

scGPT实战指南:如何用生成式AI加速你的单细胞多组学研究?

本文提供了scGPT在单细胞多组学研究中的实战指南。详细介绍了从环境部署、数据预处理到细胞类型注释与扰动预测等核心任务的操作流程。通过利用生成式AI和Transformer基础模型,scGPT能够显著加速分析,并提升细胞注释的准确性及基因调控网络推断的深度,为研究人员提供了强大的AI分析引擎。

weixin_29215815的博客 402

[java] 集合-Collection、ArrayList、LinkedList源码篇

扩容机制:当存满时候,会创建一个新的数组,新数组的长度,是原来的1.5倍,也就是长度为15.再把所有的元素,全拷贝到新数组中。举个例子: 在一开始,如果默认的长度为10的数组已经装满了,在装满的情况下,我一次性要添加100个数据很显然,10扩容1.5倍,变成15,还是不够,有序集合,这里的有序指的是存取顺序,用户可以精确控制列表中每个元素的插入位置,用户可以通过整数索引访问元素,并搜索列表中的元素。添加第二个元素时,底层创建一个结点对象,第一个结点会记录第二个结点的地址值,last会记录新结点的地址值。

2301_77946674的博客 1301

风控IV、AUC、KS python计算代码

df_temp:数据集,Y:是否逾期标签,feas_list:需要计算IV的 变量。2、 按月和不同Y 下的 IV计算。

暮雨听轩的专栏 1618

【JDK8源码】LinkedList集合

【JDK8源码】LinkedList集合LinkedList特性LinkedList数据结构源码分析层次结构属性构造函数常用方法循环 LinkedList特性 双向链表,增删快,随机访问慢(相对ArrayList) 泛型类,可存储任意类型 离散空间,不需要主动扩容 提供大量首尾操作的方法 LinkedList数据结构 private static class Node<E> { E item; Node<E> next; Node

weixin_43988801的博客 4184

APK静态分析(取证角度)——理论部分

APP是指应用程序(Application),是指能够在手机、平板电脑、电脑等移动设备上运行的软件。APP可以帮助用户进行各种功能操作,如社交媒体、游戏、购物、学习、工作等。用户可以通过应用商店或者在线下载安装APP,然后在设备上使用它们。APP的种类非常丰富,能够满足用户不同的需求和兴趣。

currify的博客 3208

SDR 和 DDR 的区别

SDR 和 DDR 的差别,最明显提现在传输速率和频率上。DDR SDRAM与SDRAM的基本结构是相似的,最根本的区别在于DDR 支持在一个时钟周期内传输两次数据,,SDR 只能传输一次数据。

串起点滴 1960

【初探Java之路 六 】集合1-ArrayList和LinkedList的使用与源码分析

ArrayList是Java集合框架中的一个动态数组实现。它就像一个会自动扩展的魔法背包,当你往里面塞更多东西时,它会自动变大。//学号//姓名//年龄//居住地return sid;return age;/*1:用输出语句完成主界面的编写2:用Scanner实现键盘录入数据3:用switch语句完成操作的选择4:用循环完成再次回到主界面*///创建集合对象,用于保存学生数据信息//用循环完成再次回到主界面//用输出语句完成主界面的编写。

z17711802963的博客 1692

【考试大纲】中级多媒体应用设计师考试大纲

中级多媒体应用设计师考试大纲

邓邓子的博客 382

Java集合之LinkedList源码篇

Java集合之LinkedList源码解析

个人博客,欢迎收藏。 1237

YOLOv13改进策略【特征提取层】| 引入注意力卷积模块RFAConv,关注感受野空间特征 助力yolov13精度提升

RFAConv:创新空间注意力和标准卷积运算感受野空间特征是针对卷积核设计的,根据卷积核大小动态生成。以3×3卷积核为例,它由非重叠滑动窗口组成,每个窗口代表一个感受野滑块。

Limiiiing的博客 361

华为OD机试真题新系统-空间占用计算(Py/Java/C/C++/Js/Go)

华为OD机试新系统机试真题 【空间占用计算】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【空间占用计算】。

qq_45776114的博客 3441

JDK集合源码之LinkedList解析

声明:尊重他人劳动成果,转载请附带原文链接! 1.LinkedList继承体系 LinkedList:LinkedList是一个以双向链表实现的List,它除了作为List使用,还可以作为队列或者栈来使用。 从继承体系可以看出,LinkedList实现了Cloneable和Serializable接口,说明其可以被克隆,也可以被序列化!同样的,LinkedList被克隆的时候,和ArrayList一样二者均是浅拷贝。 对于如何实现集合的浅拷贝和序列化,我在上一篇文章JDK集合源码之ArrayList解.

兴趣使然的草帽路飞 3980

【图像识别】基于计算机视觉实现红绿灯识别matlab代码

​ 1 简介 现如今,盲人出行依旧是一大问题.面对无处不在的红绿灯,盲人无法通过眼睛辨识红绿灯的状态,出行受阻.为了解决盲人识别红绿灯的难题,本文提出了一种基于MATLAB进行红绿灯识别的系统.对交通灯的识别主要基于对交通灯的色彩及形状特征.基于信号灯的亮度对其进行分割,提取,并设置了一种自动最优选择阈值的方法.再由HIS彩色空间的H信息识别颜色.最后根据二值化的交通灯的横坐标和纵坐标方向的投影进行形状匹配识别. 2 部分代码 clc clear all close all a=imread('m

qq_59747472的博客 2690

LinkedList集合源码

节点的基本结构: private static class Node<E> { E item; //表示该节点包含的值 Node<E> next; //表达当前节点的下一个节点 Node<E> prev; //表示当前节点的上一个节点 Node(Node<E> prev, E...

zxk082829的博客 176

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LinkedList 源码分析

LinkedList提供了一种灵活且动态的数据存储方式,适合频繁的插入和删除操作。虽然查询效率较低,但在特定场景下,它比ArrayList更具优势。理解LinkedList的内部实现和操作机制,有助于更好地选择合适的数据结构以应对不同的编程需求。

Rockivy的博客 1918

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Java 集合框架 源码浅析 与理解

Java集合框架 collection map set hashmap hashset queue

永远不要停下学习的脚步。 7024

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Java集合之LinkedList

LinkedList是实现了List和Deque接口的双向链表,实现了所有可选列表的操作,允许存放所有元素(包括null)

骑着猪猪去旅行的博客 2667

Java集合源码剖析(一)【集合框架概述、ArrayList、LinkedList

加入社区:https://bbs.youkuaiyun.com/forums/4304bb5a486d4c3ab8389e65ecb71ac0// 获取index位置的元素// 设置index位置的值为element。并返回index位置的原始值// 将“元素e”添加到Vector最后。modCount++;// 删除Vector中的元素o// 在index位置添加元素element// 删除index位置的元素,并返回index位置的原始值modCount++;

2401_86963643的博客 1294

Java集合——LinkedList源码浅析

一、继承关系 public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable List接口:可以存储重复性数据,数据可以为null,插入有序 Deque...

weixin_42738587的博客 357

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

LinkedList简介 LinkedList是基于双向循环链表(从源码中可以很容易看出)实现的,除了可以当做链表来操作外,它还可以当做栈、队列来使用。 LinkedList同样是非线程安全的,只在单线程下适合使用。 LinkedList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了Cloneable接口,能被克隆。 LinkedList源码剖析 LinkedList的源码如下(加入了比较详细的注释):

兰亭风雨的专栏 1万+

一文读懂,java list集合详解及arraylist,linkedlist集合底层源码分析

Collection集合概述是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素JDK 不提供此接口的任何直接实现.它提供更具体的子接口(如Set和List)实现创建Collection集合的对象多态的方式具体的实现类ArrayListCollection集合常用方法方法名说明添加元素从集合中移除指定的元素根据条件进行移除清空集合中的元素判断集合中是否存在指定的元素判断集合是否为空集合的长度,也就是集合中元素的个数List集合的概述。

m0_58975186的博客 1004

Java集合之LinkedList源码解析

而第二个方法 remove(Object o) 是删除指定元素,这个方法要依次遍历节点进行元素的比较,最坏情况下要比较到最后一个元素,比调用 node 方法更慢,时间复杂度为 O(n)。如上图所示,LinkedList底层使用的双向链表结构,有一个头结点和一个尾结点,双向链表意味着我们可以从头开始正向遍历,或者是从尾开始逆向遍历,并且可以针对头部和尾部进行相应的操作。首先,将last引用赋值给l,接着new了一个新节点E2,并且E2的prve指向l,接着将新节点E2赋值为last。

XING的博客 901

java linkedlist源码_java集合中LinkedList源码浅析

LinkedList就传说中的双向循环链表了。是List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。链表操作优点:1.因为每个结点记录下个结点的引用,则在进行插入和删除操作...

weixin_39556853的博客 188

九张图,探究 LinkedList 集合源码

J3 - 西行 集合(源码 # LinkedList) List 集合体系下的一个常用实现类,底层为双向链表结构,通过创建节点改变节点的前驱指针和后驱指针实现集合元素的动态改变。 下面将结合源码和本人手绘流程图的方式进行详细分析,一起来看看把! 1、LinkedList 简介 一个由 Node 节点组成的双向链表集合,可以存放任意元素包括 null 。 看其内部重要源代码(存储元素的结构): public class LinkedList<E> extends AbstractS..

技术分享、唠嗑水文、如有不周、还望海涵 842

【 java 集合】List接口常用实现类对比以及ArrayList和LinkedList源码分析

List接口继承自Collection接口,常用的List实现类有ArrayList、LinkedList、Vector。本节将大概对比一下他们三者的不同!并且分析一下源码!

阿牛的博客 1149
上一篇: 常用集合之ArrayList和Vector的区别源码浅析
下一篇: 常用集合之HashMap源码浅析
She_lock
博客等级 码龄12年 157粉丝 134原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值