牛骨文教育服务平台(让学习变的简单)
博文笔记

遍历List的同时对List进行修改

创建时间:2015-11-24 投稿人: 浏览次数:8343

先上代码:

Collection<String> list = new ArrayList<String>();
        list.add("Android");
        list.add("iPhone");
        list.add("Windows Mobile");
 
        // example 0
        Iterator<String> itr0 = list.iterator();
        while(itr0.hasNext()){
            String lang = itr0.next();
            itr0.remove();
        }
        
        // example 1        
        Iterator<String> itr1 = list.iterator();
        while(itr1.hasNext()){
            String lang = itr1.next();
            list.remove(lang);
        }
 
        // example 2
        for(int i = 0; i < list.size(); i++){
            list.remove(i);
        }
        
        // example 3
        for(String language: list){
            list.remove(language);
        }

example0,example2不会抛出ConcurrentModificationException异常;但example1,example3则会抛出ConcurrentModificationException异常;

原因分析:

example1没调用Iterator的remove方法进行删除;在itr1.next()中会检查

ourList.modCount != expectedModCount
则抛出ConcurrentModificationException异常;

@SuppressWarnings("unchecked") public E next() {
            ArrayList<E> ourList = ArrayList.this;
            int rem = remaining;
            if (ourList.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            if (rem == 0) {
                throw new NoSuchElementException();
            }
            remaining = rem - 1;
            return (E) ourList.array[removalIndex = ourList.size - rem];
        }


example3的for-each循环内部其实也是使用了Iterator来遍历Collection,它也调用了Iterator.next(),这同样也会检查(元素的)变化并抛出ConcurrentModificationException!

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。