【问题标题】:ConcurrentModificationException, i want to delete the same names in hashmap valuesConcurrentModificationException,我想删除 hashmap 值中的相同名称
【发布时间】:2014-02-21 23:28:41
【问题描述】:

我想使用这种方法删除 HashMap 中的相同名称,但是当我尝试编译我的代码时,我得到了 ConcurrentModificationException。

public static void removeTheFirstNameDuplicates(HashMap<String, String> map)
    {

        for (Map.Entry<String, String> pair : map.entrySet()){
            String name = pair.getValue();
            removeItemFromMapByValue(map, name);
        }

    }

【问题讨论】:

  • 不要混淆编译错误和运行时异常/错误。
  • 然后google一下异常和异常消息。如果我见过,这是重复的。

标签: java iterator hashmap


【解决方案1】:

当你使用这样的“增强”for循环时:

for (Map.Entry<String, String> pair : map.entrySet()){

在幕后确实有一个隐含的Iterator,每次迭代都会给你一个pairSection 14.14.2 of the JLS 状态:

增强的 for 语句相当于基本的 for 语句,形式如下:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    VariableModifiersopt TargetType Identifier =
        (TargetType) #i.next();
    Statement
}

Iterator 将抛出 ConcurrentModificationException,如果在迭代集合时有任何东西修改了集合,除非您调用 iterator's own remove() method,它会删除当前元素。您必须使用明确的Iterator

Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while (itr.hasNext())
{
    Map.Entry<String, String> pair = itr.next();
    if (yourCriteriaIsMet)
    {
        itr.remove();
    }
}

【讨论】:

    【解决方案2】:

    在迭代数据结构时不要修改它们 - 请参阅 http://docs.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2021-06-13
      • 2015-09-23
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多