编程中定义的方法报异常问题

下面是一个“关于集合的迭代删除问题”

public class  TestIterator{

        public static void main(String[] args) {

                List<String> aList = new ArrayList<String>();
                aList.add("aaa");
                aList.add("bbb");
                aList.add("asdf");
                aList.add("jvaa");
                aList.add("aaaa");
                aList.add("itcast");

                System.out.println(aList);
                delElements1(aList);
                delElements2(aList);
                delElements3(aList);
                System.out.println(aList);
        }

        public static void delElements1(List<String> aList) {
                for (String str : aList) {
                        if (str.equals("aaa")) {
                                aList.remove(str);
                        }
                }
        }

        public static void delElements2(List<String> aList){
                Iterator<String> it = aList.iterator();
                 while(it.hasNext()){
                        String str = it.next();
                        if(str.equals("aaa")){
                                aList.remove(str);
                        }
                 }
        }
       
        public static void delElements3(List<String> aList){
                        Iterator<String> it = aList.iterator();
                         while(it.hasNext()){
                        String str = it.next();
                        if(str.equals("aaa")){
                                it.remove();
                        }
                 }
        }
}
以上代码中delElements1,delElements2都会报异常:Exception in thread "main" java.util.ConcurrentModificationException,而delElements3则不会报异常,请问这是为什么呢?

答案由读者来回答。 方便 你们来思考。

posted @ 2012-07-19 00:12  龙铭洪官方网站  阅读(130)  评论(0编辑  收藏  举报