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 分钟前
RDP登录事件详细溯源分析脚本(兼容Windows PowerShell版本)
运维·网络·windows·网络安全·网络攻击模型·安全威胁分析·安全架构
井上泷奈13 分钟前
Win键失效解决方法
windows·经验分享·其他
洗紫16 分钟前
Python中的条件语句怎么使用?
python
南汐汐月23 分钟前
重生归来,我要成功 Python 高手--day35 深度学习 Pytorch
pytorch·python·深度学习
java1234_小锋28 分钟前
[免费]基于Python的深度学习豆瓣电影数据可视化+情感分析推荐系统(Flask+Vue+LSTM+scrapy)【论文+源码+SQL脚本】
python·信息可视化·flask·电影数据可视化
网硕互联的小客服1 小时前
Windows2008 如何禁用FSO?
运维·服务器·网络·windows·安全
PieroPc1 小时前
一个基于Python Streamlit sqlite3 的销售单管理系统,提供商品管理、客户管理、销售单管理及打印,和应收对账单等功能
python·oracle·sqlite·streamlit
月下倩影时1 小时前
视觉进阶篇—— PyTorch 安装
人工智能·pytorch·python
不惑_1 小时前
[特殊字符] 在 Windows 上设置 SQLite
数据库·windows·sqlite
Valueyou242 小时前
论文阅读——CenterNet
论文阅读·python·opencv·目标检测·计算机视觉