从哈希图中删除元素时发生java.util.ConcurrentModificationException [英] java.util.ConcurrentModificationException when removing elements from a hashmap

查看:48
本文介绍了从哈希图中删除元素时发生java.util.ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 HashMap 类,并编写了这个简单的程序.这段代码非常适合在哈希图中添加元素,而在从哈希图中删除元素时,我遇到了 java.util.ConcurrentModificationException 例如,这是我的终端机的副本,

I am learning about HashMap class and wrote this simple program. this code works good for adding elements to the hashmap and while removing elements from the hashmap , I am encountering java.util.ConcurrentModificationException for example here is a copy of my terminal,

[ravi@doom test]$ java TestHashMap 
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :1

 Key : A

 Value : 1
Key/Value : (A,1) added to storage.
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :1

 Key : B

 Value : 2
Key/Value : (B,2) added to storage.
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :1

 Key : C

 Value : 3
Key/Value : (C,3) added to storage.
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :1

 Key : D

 Value : 4
Key/Value : (D,4) added to storage.
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :4
( D , 4 );
( A , 1 );
( B , 2 );
( C , 3 );
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :2
Key to REMOVE : 
D
Pair (D,4) Removed.
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :4
( A , 1 );
( B , 2 );
( C , 3 );
.....MENU.....
1. Add
2. remove key
3. remove value
4. display
7. Exit
Your choice :3
Enter Value to remove : 2
Key : B Removed.
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
    at java.util.HashMap$EntryIterator.next(HashMap.java:962)
    at java.util.HashMap$EntryIterator.next(HashMap.java:960)
    at TestHashMap.start(TestHashMap.java:60)
    at TestHashMap.main(TestHashMap.java:87)
ABRT problem creation: 'success'

代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class TestHashMap
{
    private Map<String,Integer> map;
    public TestHashMap()
    {
        map = new HashMap<String,Integer>();
    }
    public void displayMenu()
    {
        System.out.println(".....MENU.....");
        System.out.println("1. Add");
        System.out.println("2. remove key");
        System.out.println("3. remove value");
        System.out.println("4. display");
        System.out.println("7. Exit");
        System.out.print("Your choice :");
    }
    public void start()
    {
        Scanner input = new Scanner(System.in);
        int menuChoice,value;
        String key;
        while(true)
        {
            displayMenu();
            menuChoice = input.nextInt();
            switch(menuChoice)
            {
                case 1:
                    System.out.print("\n Key : ");
                    input.nextLine();
                    key = input.nextLine();
                    System.out.print("\n Value : ");
                    value = input.nextInt();
                    map.put(key,new Integer(value));
                    System.out.println("Key/Value : ("+key+","+value+") added to storage.");
                break;
                case 2:
                    System.out.println("Key to REMOVE : ");
                    input.nextLine();
                    key = input.nextLine();
                    Integer v = map.get(key);
                    if(v == null)
                        System.out.println("No value exists for key "+key);
                    else
                    {
                        map.remove(key);
                        System.out.println("Pair ("+key+","+v.intValue()+") Removed.");
                    }
                    break;
                case 3:
                    System.out.print("Enter Value to remove : ");
                    value = input.nextInt();
                    if(map.containsValue(new Integer(value)))
                    {
                        for(Map.Entry<String,Integer> entry : map.entrySet() )
                        {
                            if(entry.getValue().intValue() == value)
                            {
                                System.out.println("Key : "+entry.getKey()+" Removed.");
                                map.remove(entry.getKey());
                            }
                        }
                    }
                break;
                case 4:
                    for(Map.Entry<String,Integer> entry : map.entrySet() )
                    {
                        System.out.println("( "+entry.getKey()+" , "+entry.getValue()+" );");
                    }
                break;
                case 7:
                    input.close();
                    System.exit(0);
                default:
                    System.out.println("Invalid Choice !");
            }
        }
    }
    public static void main(String args[])
    {
        TestHashMap thm = new TestHashMap();
        thm.start();
    }
}

更新:工作代码

感谢你们两个( rgettman Nathan Hughes ).

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Iterator;

class TestHashMap
{
    private Map<String,Integer> map;
    public TestHashMap()
    {
        map = new HashMap<String,Integer>();
    }
    public void displayMenu()
    {
        System.out.println(".....MENU.....");
        System.out.println("1. Add");
        System.out.println("2. remove key");
        System.out.println("3. remove value");
        System.out.println("4. display");
        System.out.println("7. Exit");
        System.out.print("Your choice :");
    }
    public void start()
    {
        Scanner input = new Scanner(System.in);
        int menuChoice,value;
        String key;
        while(true)
        {
            displayMenu();
            menuChoice = input.nextInt();
            switch(menuChoice)
            {
                case 1:
                    System.out.print("\n Key : ");
                    input.nextLine();
                    key = input.nextLine();
                    System.out.print("\n Value : ");
                    value = input.nextInt();
                    map.put(key,new Integer(value));
                    System.out.println("Key/Value : ("+key+","+value+") added to storage.");
                break;
                case 2:
                    System.out.println("Key to REMOVE : ");
                    input.nextLine();
                    key = input.nextLine();
                    Integer v = map.get(key);
                    if(v == null)
                        System.out.println("No value exists for key "+key);
                    else
                    {
                        map.remove(key);
                        System.out.println("Pair ("+key+","+v.intValue()+") Removed.");
                    }
                    break;
                case 3:
                    System.out.print("Enter Value to remove : ");
                    value = input.nextInt();
                    if(map.containsValue(new Integer(value)))
                    {
                        for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();it.hasNext();) 
                        {
                            Map.Entry<String,Integer> x = it.next();
                            if(x.getValue().intValue() == value)
                            {
                                key = x.getKey();
                                it.remove();
                                System.out.println("Key : "+key+" Removed.");
                            }
                        }
                    }
                break;
                case 4:
                    for(Map.Entry<String,Integer> entry : map.entrySet() )
                    {
                        System.out.println("( "+entry.getKey()+" , "+entry.getValue()+" );");
                    }
                break;
                case 7:
                    input.close();
                    System.exit(0);
                default:
                    System.out.println("Invalid Choice !");
            }
        }
    }
    public static void main(String args[])
    {
        TestHashMap thm = new TestHashMap();
        thm.start();
    }
}

推荐答案

您的for循环获取map.entrySet并在其上使用迭代器浏览地图条目(此for循环版本需要Iterable,它从Iterable获取迭代器).当您在地图上使用迭代器,但不使用该迭代器将其从地图中删除时,会收到ConcurrentModificationException.那是地图告诉迭代器它已经过时了.

Your for-loop gets the map.entrySet and uses the iterator on it to work through the map entries (this version of the for-loop requires an Iterable, it gets the iterator from the Iterable). When you are using an iterator on a map, but remove things from the map without using that iterator, you get the ConcurrentModificationException. That is the map telling the iterator that it's out of date.

您可以使用迭代器显式编写一个for循环,如下所示:

You can write a for loop using the iterator explicitly, like this:

for (Iterator<Map.Entry<String, Integer> it = map.entrySet().iterator();
it.hasNext();) {

并在需要删除条目时使用迭代器的remove方法.

and use the iterator's remove method when you need to delete an entry.

这篇关于从哈希图中删除元素时发生java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆