【问题标题】:Delete entry from HashMap [duplicate]从 HashMap 中删除条目 [重复]
【发布时间】:2017-03-30 11:32:48
【问题描述】:

我有一个 HashMap:

public static Map<String, Set<String>> adjMap = new HashMap<String, Set<String>>();
adjMap.put(title, new HashSet<String>());
adjMap.get(title).add(cutTitle(graphLink));

现在我想从不包含作为键的值 (HashSet) 中删除所有条目。

到目前为止,这是我的代码:

for(String s: adjMap.keySet()){
    for(Set<String> s1: adjMap.values()){
        for(String s2: s1){
            if(!s.contains(s2)){
                s1.remove(s2);
            }
        }
    }
}

但我得到一个例外:

线程“主”java.util.ConcurrentModificationException 中的异常

【问题讨论】:

  • 您正在尝试修改 Foreach 循环中的 Hashset,但它使用的是自己的迭代器。
  • 使用ConcurrentHashMap 而不是HashMap

标签: java hashmap


【解决方案1】:

迭代你的地图

Iterator it = adjMap.entrySet().iterator();
    while (it.hasNext())
    {
       Entry item = it.next();
       map.remove(item.getKey());
    }

【讨论】:

    【解决方案2】:

    我认为 for-each 循环不允许改变迭代对象。要删除条目,您应该使用迭代器。

    map-Iteration 为例。

    【讨论】:

      【解决方案3】:

      您可以改用ConcurrentHashMap,或创建HashMap 的副本并对副本进行任何更改。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 1970-01-01
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多