我是靠谱客的博主 超帅热狗,这篇文章主要介绍Java foreach遍历时不能用remove Exception in thread “main“ java.util.ConcurrentModificationException,现在分享给大家,希望可以做个参考。

Java foreach遍历时不能用remove,会报错

Exception in thread “main” java.util.ConcurrentModificationException

	HashMap<String, String> map = new HashMap<>();
	
	map.put("A", "1");
	map.put("B", "2");
	map.put("C", "3");
	// you can not remove item in map when you use the iterator of map
	for(Entry<String,String> entry : map.entrySet()){
		if(!entry.getValue().equals("1")){
		map.remove(entry.getKey());
		}
	}
	
	// if you want to remove items, collect them first, then remove them by
	// this way. 
	List<String> removeKeys = new ArrayList<String>();
	for (Entry<String, String> entry : map.entrySet()) {
		if (!entry.getValue().equals("1")) {
		removeKeys.add(entry.getKey());
		}
	}
	for (String removeKey : removeKeys) {
	map.remove(removeKey);
	}

迭代器配合while删除元素

// 引入 ArrayList 和 Iterator 类
import java.util.ArrayList;
import java.util.Iterator;

public class RunoobTest {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(12);
        numbers.add(8);
        numbers.add(2);
        numbers.add(23);
        Iterator<Integer> it = numbers.iterator();
        while(it.hasNext()) {
            Integer i = it.next();
            if(i < 10) {  
                it.remove();  // 删除小于 10 的元素
            }
        }
        System.out.println(numbers);
    }
}

最后

以上就是超帅热狗最近收集整理的关于Java foreach遍历时不能用remove Exception in thread “main“ java.util.ConcurrentModificationException的全部内容,更多相关Java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(111)

评论列表共有 0 条评论

立即
投稿
返回
顶部