zoukankan      html  css  js  c++  java
  • Java处理java.util.ConcurrentModificationException异常

    代码:

    public static void reduce(HashMap<String, Integer> hashMap, final Integer count) {
        Iterator<String> iter = hashMap.keySet().iterator();
        String key;
    
        while(iter.hasNext()) {
            key = iter.next();
    
            if (!hashMap.get(key).equals(count)) {
                hashMap.remove(key);
            }
        }
        return hashMap;
    }

    异常:

    Exception in thread "main" java.util.ConcurrentModificationException

    原因:

      在迭代的过程中进行了add(),remove()操作。其实仔细想想也能理解,如果在迭代中使用remove(),那第二轮循环时的next()究竟指向谁?!

    方法:

      使用迭代器对象来移除该对象.

    public static void reduce(HashMap<String, Integer> hashMap, final Integer count) {
        Iterator<String> iter = hashMap.keySet().iterator();
        String key;
    
        while(iter.hasNext()) {
            key = iter.next();
    
            if (!hashMap.get(key).equals(count)) {
                // hashMap.remove(key);
           iter.remove();   // 这里改用迭代器对象来移除! }   }
    return hashMap; }
  • 相关阅读:
    gvim : invalid input string
    端口
    Sequence Overview
    vi的使用
    Ubuntu安装CodeBlocks相关问题总结
    中断
    Ubuntu Software Repository
    UVA 12299 RMQ with Shifts
    UVA 12293 Box Game
    POJ 3468 A Simple Problem with Integers (1)
  • 原文地址:https://www.cnblogs.com/yrqiang/p/5344531.html
Copyright © 2011-2022 走看看