0%

ConcurrentModificationException异常的解决

当使用Iterator迭代一个List时,如果在迭代过程中直接调用List的remove方法删除List的子元素,就会抛出ConcurrentModificationException。因为Java不允许在迭代过程中修改被迭代的List. 解决方法:使用Iterator的remove方法删除该子元素。示例代码:

        ArrayList ss = new ArrayList();
        ss.add("asdf");
        ss.add("efsvfg");
        ss.add("fff");
        ss.add("efsdfa");
        ss.add("wfesvwe");

        for (Iterator it = ss.iterator(); it.hasNext();) {
            String obj = it.next().toString();
            System.out.println(obj);
            if (obj.equals("asdf")) {
                //ss.remove(obj); 这样直接删除该元素,就会抛ConcurrentModificationException异常
                it.remove();//必须通过Iterator的remove方法删除
            }
        }
        System.out.println();
        for (Iterator it = ss.iterator(); it.hasNext();) {
            String obj = it.next().toString();
            System.out.println(obj);
        }
        //查看删除后的结果