首页 > 技术文章 > Collection并发问题分析与解决

theStone 2022-03-17 16:05 原文

最近面试被问了一个很nice的问题,collection遍历操作删除元素,有几种方式。自己的求知不怎么高,以至于只知道个大概,今天抽空详细了解并分析一下原因,顺便分享一下有哪些。

        ArrayList<String> strLs = new ArrayList<>();
        strLs.add("stone1");
        strLs.add("stone2");
        strLs.add("stone3");
        strLs.add("stone4");
        strLs.add("stone5");

//      因为遍历的时候,删除了一个元素,所以后续的元素的索引相对于以前的索引-1了
        for (int i = 0; i < strLs.size(); i++) {
            String temp = strLs.get(i);
            if (temp.equals("stone3")){
                strLs.remove("stone3");
                i--;
                continue;
            }
            System.out.println(temp);
        }

//      数组反向遍历,删除中间的数组,前面的索引还是不会改变的
        for (int i = strLs.size() - 1; i >= 0; i--) {
            String temp = strLs.get(i);
            if (temp.equals("stone3")){
                strLs.remove("stone3");
                continue;
            }
            System.out.println(temp);
        }

//        以上的问题是因为通过改变数组的大小,而造成所以可能变化,当用迭代器就不会有这中问题
        Iterator<String> iterator = strLs.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if (next.equals("stone3"))
                iterator.remove();
            else
                System.out.println(next);
        }
    }

推荐阅读