ArrayList中进行删除操作引发的问题
2024-09-04 00:07:33
1、普通for遍历
for(int i=0;i<list.size();i++){ if(list.get(i).equals("a")) list.remove(i); }
【存在的问题】:
当删除其中一个元素时,list的大小发生变化,再次删除时,索引会发生变化,会导致结果出错;
2、foreach遍历
for(String x:list){ if(x.equals("a")) list.remove(x); }
【存在的问题】:
会发生ConcurrentModificationException,原因在于expectedModCount与modCount值不同导致异常;
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { protected transient int modCount = 0;
}
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; =========expectedModCount=modCount(父类的modCount=0)}
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
private void fastRemove(int index) { modCount++; ========此处modCount+1
int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work}
final void checkForComodification() { if (modCount != expectedModCount) ========此处进行modCount与expectedModCount作比较 throw new ConcurrentModificationException();}
}
3、iterator遍历
Iterator<String> it = list.iterator(); while(it.hasNext()){ String x = it.next(); if(x.equals("a")){ // list.remove(x); =========用list.remove(x)仍会抛出异常,原因同foreach it.remove(); =======正确方法:使用iterator的remove } }
最新文章
- github page
- 可在广域网部署运行的QQ高仿版 -- GG叽叽V3.0,完善基础功能(源码)
- 选择Nodejs的N个理由
- uafxcwd.lib(afxmem.obj) : error LNK2005 解决方法
- Swift编程规范
- jQuery队列控制方法详解queue()/dequeue()/clearQueue()
- iptables vpn
- MySQL之库相关操作
- Vue 开发经验总结
- 2018牛客网暑假ACM多校训练赛(第五场)F take 树状数组,期望
- 恶心github 下载慢
- 《温故而知新》JAVA基础八
- mysqli字符编码
- git 恢复单个文件的历史版本
- python start
- C# 集合-并发处理-锁OR线程 (转载)
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)(略有修改)
- 用COS实现文件上传
- 洛谷P3812 【模板】线性基
- lintcode-171-乱序字符串