List知识总结

ArrayList:

java 复制代码
1  ArrayList扩容底层用到的是;System.arraycopy.
2  扩容的长度计算;int newCapacity = oldCapacity + (oldCapacity >> 1);,旧容量 + 旧容量右移1位,这相当于扩容为原
来容量的(int)3/2.
3  ArrayList<String> strings = new ArrayList<>(10);
没有数据填充时进行插入数据,list.add(2,2);会抛异常IndexOutOfBoundsException

LinkedList:

java 复制代码
  三种插入方式:
  LinkedList<String> strings1 = new LinkedList<>(Arrays.asList("1"));
  LinkedList<String> strings2 = new LinkedList<>(Collections.nCopies(10, "1"));
  LinkedList<String> strings3 = new LinkedList<String>() {
      {
           add("1");
           add("3");
       }
   };

对比ArrayList和LinkedList:

java 复制代码
1 头插:ArrayList需要做大量的位移和复制操作,耗时更长
2 尾插:ArrayList 尾插时,是不需要数据位移的,比较耗时的是数
据的扩容时,数据超过百万的时候尾插法LinkedList耗时更长,主要在创建节点上.
3 中间插入:Linkedlist在中间插入时,遍历寻找位置还是非常耗时了
  ArrayList可以使用copy-on-write技术来避免频繁的扩容和移动元素

List遍历5种方式:

java 复制代码
1 普通for循环
2 增强for循环
   for (Integer itr : list) {
        xx += itr;
    }
3 迭代器
    Iterator<Integer> iterator = list.iterator();
    while (iterator.hasNext()) {
        Integer next = iterator.next();
        xx += next;
    }
4 foreach
  list.forEach(integer -> {
        xx += integer;
    });
5  stream
   list.stream().forEach(integer -> {
        xx += integer;
    });

在集合的首位有大量的插入、删除以及获取操作,那么可以使用LinkedList,

LinkedList的链表结构不一定会比ArrayList节省空间,首先它所占用的内存不是连续的,其次他还需要大量的实例化对象创造节点

综合来看,如果需要频繁进行随机访问元素的操作,或者对内存占用要求较高,那么应选择ArrayList。如果需要频繁进行插入或删除元素的操作,或者不需要随机访问元素,那么应选择LinkedList。

相关推荐
火云洞红孩儿7 小时前
告别界面孤岛:PyMe如何用一站式流程重塑Python GUI开发?
开发语言·python
攻城狮7号7 小时前
不懂代码也能造?TRAE+GLM-4.6 手把手教你搭心理咨询智能客服小程序
python·小程序·uni-app·vue·trae·glm我的编程搭子·glm-4.6
叫我辉哥e17 小时前
新手进阶Python:办公看板集成ERP跨系统同步+自动备份+AI异常复盘
开发语言·人工智能·python
私人珍藏库7 小时前
[Windows] 桌面整理 Desk Tidy v1.2.3
windows·工具·软件·win·多功能
C++ 老炮儿的技术栈8 小时前
不调用C++/C的字符串库函数,编写函数strcpy
c语言·开发语言·c++·windows·git·postman·visual studio
布局呆星8 小时前
闭包与装饰器
开发语言·python
全栈测试笔记8 小时前
异步函数与异步生成器
linux·服务器·前端·数据库·python
weixin_462446238 小时前
Linux 下使用 xfreerdp3 远程连接 Windows(从安装到实战使用)
linux·运维·windows
木头左8 小时前
基于Backtrader框架的指数期权备兑策略实现与分析
python
素心如月桠9 小时前
cmd 输入 python --version 输出为空(windows11系统安装python后执行python --version没反应)
python