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。

相关推荐
不知名的老吴1 分钟前
返回None还是空集合?防御式编程的关键细节
开发语言·python
李昊哲小课20 分钟前
Python办公自动化教程 - 第5章 图表创建 - 让数据可视化
python·信息可视化·数据分析·数据可视化·openpyxl
chushiyunen27 分钟前
python pygame实现贪食蛇
开发语言·python·pygame
Dream of maid28 分钟前
Python-基础2(流程控制)
python
Lenyiin2 小时前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
涛声依旧393162 小时前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘
kcuwu.3 小时前
Python进阶:生成器与协程,高效并发编程的核心实践
windows·python·php
XiaoQiao6669993 小时前
python 简单题目练手【详解版】【1】
开发语言·python
ZC跨境爬虫3 小时前
极验滑动验证码自动化实战:背景提取、缺口定位与Playwright滑动模拟
前端·爬虫·python·自动化
智算菩萨3 小时前
【Python图像处理】2 数字图像基础与Python图像表示
开发语言·图像处理·python