jack-zheng
6/6/2018 - 7:54 AM

java, remove element in collection

java, remove element in collection

Remove Element In Collection

我记得在python 笔记中也有类似的问题,说明这是一个所有语言都通用的道理, 不要在for 循环中remove element, 用 iterator 来代替

/**
     * java.util.ConcurrentModificationException
     * at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
     * at java.util.ArrayList$Itr.next(ArrayList.java:851)
     * xxx.xxx.xxx.test(xxxTest.java:230)
     */
    @Test
    public void test01() {
        List<String> a = new ArrayList<>();
        a.add("1");
        a.add("2");
        a.add("3");
        a.add("4");
        for (String sub : a) {
            if (sub.equals("2")) {
                a.remove("2");
            }
        }
    }

    /**
     * The correct way to remove an element in iterator
     */
    @Test
    public void test02() {
        List<String> a = new ArrayList<>();
        a.add("1");
        a.add("2");
        a.add("3");
        a.add("4");
        Iterator<String> i = a.iterator();
        while (i.hasNext()) {
            String ret = i.next();
            if (ret.equals("2")) {
                i.remove();
            }
        }

        for (String sub : a) {
            System.out.println("sub: " + sub);
        }
    }