ArrayList for循环remove元素 , 没有抛出异常
来源:互联网 发布:百度地图数据采集器 编辑:程序博客网 时间:2024/04/29 09:13
示例代码:
public class TestList { public static void main(String[] args) { List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); for (String tmp : a) { if ("2".equals(tmp)) { a.remove(tmp); } } System.out.println(a); }}
这个示例运行最后运行成功. 但是 为什么没有抛出ConcurrentModificationException异常呢?
查看代码后发现 , 问题出在这里,
当我们遍历到 , 最后一项前一项的时候 , 这个时候size依然是3 . 而ArrayList的Iterator这里,
public boolean hasNext() { return cursor != size; }这里判断是否还有下一项.这里cursor是1. 很显然不等于size.
所以进入next
public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }next里, cursor这时候变为2 .
接下来我们删除这一项
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; }这里进入到fastRemove.
private void fastRemove(int index) { modCount++; 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 }modCount确实是++了, 但是我们的size这时候也做了--size操作,导致size变为2.
那么下次hasNext的时候判断cursor!=size , 返回的是false. 于是其实根本没有遍历到最后一项, 从而也没有做checkForComodification的操作, 从而这里不报错.
0 0
- ArrayList for循环remove元素 , 没有抛出异常
- ArrayList在for循环中使用remove方法移除元素
- for循环删除(ArrayList.remove)报错及解决办法
- for循环删除(ArrayList.remove)报错及解决办法
- easyUI accordion 使用和remove方法 for循环的异常
- android 开发 ArrayList remove异常
- Java数组第一次remove对象抛出异常
- 抛出异常 For input string: ""
- 在for循环中增加删除集合元素没有效果
- for循环删除(ArrayList.remove)及改进方法及对象在内存中的理解
- for循环删除(ArrayList.remove)及改进方法及对象在内存中的理解
- 项目中执行ArrayList.remove() 抛出java.lang.UnsupportedOperationException
- ArrayList循环遍历删除元素
- 如果catch没有异常抛出怎么办
- ArrayList循环遍历并删除元素时报java.util.ConcurrentModificationException异常
- java中在for循环中remove元素时的陷阱
- 用for循环来删除ArrayList集合中的所有元素所遇到的问题
- 为什么不能在ArrayList的For-Each循环中删除元素
- LeetCode Database(175-180)
- Java和Maven的Cloud Bigtable HBase 客户端配置
- 算法和算法实现
- git本地免密码和账号pull、push
- linux习题60
- ArrayList for循环remove元素 , 没有抛出异常
- swagger
- 命令查看IPV6的IP,路由,邻居信息
- 链表删除,反序操作等
- Cookie扫盲贴
- 自定义Loading Dialog
- 涉及的物理、数学公式及计算过程
- ubuntu或者deepin的一些常用操作命令
- mybatis实现mapper文件热部署