java 迭代的陷阱

 

复制代码
    /**
     * 关于迭代器,有一种常见的误用,就是在迭代的中间调用容器的删除方法。
     * 但运行时会抛出异常:java.util.ConcurrentModificationException
     *
     * 发生了并发修改异常,为什么呢?因为迭代器内部会维护一些索引位置相关的数据,要求在迭代过程中,容器不能发生结构性变化,否则这些索引位置就失效了。
     * 所谓结构性变化就是添加、插入和删除元素,只是修改元素内容不算结构性变化。
     *
     * @param list
     */
    public void remove(ArrayList<Integer> list) {
        for (Integer a : list) {
            if (a <= 100) {
                list.remove(a);
            }
        }
    }
复制代码

 

复制代码
/**
     * 如何避免异常呢?可以使用迭代器的remove方法
     *
     * @param list
     */
    public static void remove2(ArrayList<Integer> list) {
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()) {
            if (it.next() <= 100) {
                it.remove();
            }
        }
    }
复制代码

 

复制代码
public static void main(String[] args) {

        ArrayList<Integer> intList = new ArrayList<Integer>();
        intList.add(11);
        intList.add(456);
        intList.add(789);

        Test test = new Test();
        // test.remove(intList);
        test.remove2(intList);


    }
复制代码

 

posted @   草木物语  阅读(273)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示