网站首页 > 技术文章 正文
List可以一边遍历一边修改元素吗?
核心答案
List 能否边遍历边修改,取决于两个因素:
- 集合的实现机制 (fail-fast 或 fail-safe)
- 遍历的方式 (增强for、Iterator、索引遍历等)
详细分析
1. fail-fast集合(ArrayList、LinkedList)
1.1 什么是fail-fast?
- 定义 :快速失败机制,在检测到并发修改时立即抛出异常
- 实现 :通过 modCount 计数器检测结构性修改 #技术分享
- 目的 :避免在并发修改时产生不确定的行为
1.2 不同遍历方式的表现
增强for循环 - 不能修改
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String item : list) { if ("B".equals(item)) { list.remove(item); } }
Iterator遍历 - 有条件修改
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if ("B".equals(item)) {
// list.remove(item); // 直接修改集合会抛异常
iterator.remove(); // 使用Iterator的remove方法
}
}
索引遍历 - 可以修改(需注意索引)
for (int i = 0; i < list.size(); i++) {
if ("B".equals(list.get(i))) {
list.remove(i);
i--;
}
}
for (int i = list.size() - 1; i >= 0; i--) { if ("B".equals(list.get(i))) { list.remove(i); } }
Stream forEach - 不能修改
list.stream().forEach(item -> {
if ("B".equals(item)) {
list.remove(item);
}
});
1.3 fail-fast原理解析
public abstract class AbstractList<E> {
protected transient int modCount = 0;
private class Itr implements Iterator<E> {
int expectedModCount = modCount;
public E next() {
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public void remove() {
expectedModCount = modCount;
}
}
}
2. fail-safe集合(CopyOnWriteArrayList)
2.1 什么是fail-safe?
- 定义 :安全失败机制,允许在遍历时修改集合
- 实现 :遍历的是集合的快照(副本)
- 特点 :修改对当前遍历不可见
2.2 所有遍历方式都可以修改
增强for循环
List<String> list = new CopyOnWriteArrayList<>(Arrays.asList("A", "B", "C"));
for (String item : list) { if ("B".equals(item)) { list.remove(item); list.add("D"); } }
Iterator遍历
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
if ("B".equals(item)) {
list.remove(item); // 可以
// it.remove(); // 注意:不支持Iterator.remove()
}
}
2.3 fail-safe原理解析
public class CopyOnWriteArrayList<E> {
private volatile Object[] array;
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
Object[] newElements = new Object[elements.length - 1];
setArray(newElements);
return oldValue;
} finally {
lock.unlock();
}
}
public Iterator<E> iterator() {
return new COWIterator<E>(getArray(), 0);
}
static final class COWIterator<E> implements Iterator<E> {
private final Object[] snapshot;
private COWIterator(Object[] elements, int initialCursor) {
snapshot = elements;
}
}
}
对比总结表
| 特性 | fail-fast (ArrayList) | fail-safe (CopyOnWriteArrayList) | | ---
| 增强 for 循环修改 | 抛异常 | 可以 | | Iterator.remove() | 支持 | 不支持 | | 直接修改集合 | 抛异常 | 可以 | | 修改可见性 | 立即可见 | 对当前遍历不可见 | | 性能 | 读写都快 | 写操作慢(复制数组) | | 内存占用 | 低 | 高(维护副本) | | 适用场景 | 单线程/读写均衡 | 读多写少的并发场景 |
猜你喜欢
- 2025-10-23 JAVA中ArrayList、LinkedList及CopyOnWriteArrayList实现原理
- 2025-10-23 Java 开发必看!ArrayList 初始化为啥要指定容量?
- 2025-10-23 Java 开发者必看!3 个基础技能应用坑,90% 的人都踩过
- 2025-10-23 Java ArrayList基本操作及高级用法
- 2025-10-23 Python:array数组比列表list更高效
- 2024-08-12 精解四大集合框架:List核心知识总结
- 2024-08-12 如何在 Flutter 中将 Map/Array 列表转换为 JSON 字符串
- 2024-08-12 夯实基础:Java 中初始化 List 集合的 6 种方式你都知道吧?
- 2024-08-12 Java基础-15总结数组,Collection,List
- 2024-08-12 并发中的List集合(并发集合和普通集合如何区别?)
- 最近发表
-
- 聊一下 gRPC 的 C++ 异步编程_grpc 异步流模式
- [原创首发]安全日志管理中心实战(3)——开源NIDS之suricata部署
- 超详细手把手搭建在ubuntu系统的FFmpeg环境
- Nginx运维之路(Docker多段构建新版本并增加第三方模
- 92.1K小星星,一款开源免费的远程桌面,让你告别付费远程控制!
- Go 人脸识别教程_piwigo人脸识别
- 安卓手机安装Termux——搭建移动服务器
- ubuntu 安装开发环境(c/c++ 15)_ubuntu安装c++编译器
- Rust开发环境搭建指南:从安装到镜像配置的零坑实践
- Windows系统安装VirtualBox构造本地Linux开发环境
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (77)
- vector线程安全吗 (73)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)