【Java笔记】LinkedList 底层结构

一、LinkedList 的全面说明

  1. LinkedList底层实现了双向链表和双端队列特点
  2. 可以添加任意元素(元素可以重复),包括null
  3. 线程不安全,没有实现同步

二、LinkedList 的底层操作机制

三、LinkedList的增删改查案例

public class LinkedListCRUD {

public static void main(String[] args) {

LinkedList linkedList = new LinkedList();

linkedList.add(1);

linkedList.add(2);

linkedList.add(3);

System.out.println("linkedList=" + linkedList);

//演示一个删除结点的

linkedList.remove(); // 这里默认删除的是第一个结点

//linkedList.remove(2);

System.out.println("linkedList=" + linkedList);

//修改某个结点对象

linkedList.set(1, 999);

System.out.println("linkedList=" + linkedList);

//得到某个结点对象

//get(1) 是得到双向链表的第二个对象韩顺平循序渐进学 Java 零基础

第 636页

Object o = linkedList.get(1);

System.out.println(o);//999

//因为 LinkedList 是 实现了 List 接口, 遍历方式

System.out.println("=LinkeList 遍历迭代器==");

Iterator iterator = linkedList.iterator();

while (iterator.hasNext()) {

Object next = iterator.next();

System.out.println("next=" + next);

}

System.out.println("=LinkeList 遍历增强 for==");

for (Object o1 : linkedList) {

System.out.println("o1=" + o1);

}

System.out.println("=LinkeList 遍历普通 for==");

for (int i = 0; i < linkedList.size(); i++) {

System.out.println(linkedList.get(i));

}

//老韩源码阅读. /* 1. LinkedList linkedList = new LinkedList();

public LinkedList() {}

  1. 这时 linkeList 的属性 first = null last = null韩顺平循序渐进学 Java 零基础

  2. 执行 添加

public boolean add(E e) {

linkLast(e);

return true;

}

4.将新的结点,加入到双向链表的最后

void linkLast(E e) {

final Node l = last;

final Node newNode = new Node<>(l, e, null);

last = newNode;

if (l == null)

first = newNode;

else

l.next = newNode;

size++;

modCount++;

}
/
/

老韩读源码 linkedList.remove(); // 这里默认删除的是第一个结点

  1. 执行 removeFirst
    public E remove() {
    return removeFirst();
    }韩顺平循序渐进学 Java 零基础
    第 638页
  2. 执行
    public E removeFirst() {
    final Node f = first;
    if (f == null)
    throw new NoSuchElementException();
    return unlinkFirst(f);
    }
  3. 执行 unlinkFirst, 将 f 指向的双向链表的第一个结点拿掉
    private E unlinkFirst(Node f) {
    // assert f == first && f != null;
    final E element = f.item;
    final Node 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;
    }
    */
    }
    }
相关推荐
yoyo_zzm4 分钟前
Laravel6.x新特性全解析
java·spring boot·后端
AIFarmer11 分钟前
【无标题】
开发语言·c++·算法
Nick_zcy16 分钟前
小说在线阅读网站和小说管理系统 · 功能全解析
java·后端·python·springboot·ruoyi
源码宝19 分钟前
基于 SpringBoot + Vue 的医院随访系统:技术架构与功能实现
java·vue.js·spring boot·架构·源码·随访系统·随访管理
昇腾CANN25 分钟前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann
沐知全栈开发36 分钟前
ionic 手势事件详解
开发语言
ZhiqianXia1 小时前
《The Design of Design》阅读笔记
前端·笔记·microsoft
lsx2024061 小时前
Bootstrap 按钮
开发语言
qinqinzhang1 小时前
Java 中的 IoC、AOP、MVC
java
神仙别闹1 小时前
基于 Python 实现 BERT 的情感分析模型
开发语言·python·bert