Java - Exception in thread “main” java.util.ConcurrentModificationException

后端 未结 7 1679
广开言路
广开言路 2021-01-07 14:54

Is there any way I can modify the HashMap values of a particular key while iterating over it?

A sample program is given below:

public st         


        
相关标签:
7条回答
  • 2021-01-07 15:21

    Concurrent Modification in programming means to modify an object concurrently when another task is already running over it. Fail Fast And Fail Safe Iterators in Java Iterators in java are used to iterate over the Collection objects. Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Please use ConcurrentHashMap if you want to modify in between.

    0 讨论(0)
  • 2021-01-07 15:27

    If you want to add to the original ArrayList, then iterate through it on your own:

    final ArrayList<String> arr = hm.get(1);
    final int size = arr.size();
    
    // this will add size number of "hello" strings to ArrayList arr
    for(int i = 0; i < size; ++i){
        // you don't appear to ever use this value
        final String s = arr.get(i);
    
        // do something to arr
        arr.add("hello");
    }
    
    0 讨论(0)
  • 2021-01-07 15:31

    If try to modify while iterating your list you will get this Exception.

    for(String s:hm.get(1)){ // iterate 
        hm.get(1).add("hello");//modify
    }
    

    Both operation affect to hm

    You don't need to iterate here. Just use

    hm.get(1).add("hello");
    
    0 讨论(0)
  • 2021-01-07 15:34

    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

    Below peice of code is causing the problem.

    for(String s:hm.get(1)){
            hm.get(1).add("hello");
        }
    

    You are iterating and modifying the same. Avoid this by creating new ArrayList

      ArrayList<String> ar1 = new ArrayList<String>();
    
    for (String s : hm.get(1)) {
                ar1.add("hello");
            }
    

    have a read here

    0 讨论(0)
  • 2021-01-07 15:39

    The problem in the code your presented isn't modifying the HashMap, it's modifying the ArrayList while iterating it. You can avoid this exception if you use ar's ListIterator instead of using an enhanced for loop:

    for (ListIterator<String> i = ar.listIterator(); i.hasNext(); i.next()) {
        i.add("hello");
    } 
    
    0 讨论(0)
  • 2021-01-07 15:40

    When we are trying to modify collection object while iterating then we get this exception. Check following code:

    for(String str : stringList){ 
       stringList.add("Test");
    }
    

    So in above we get runtime exception.

    Solution

    Use iterator over For-Each loop, like:

    static void filter(Collection<?> c) {
        for (Iterator<?> it = c.iterator(); it.hasNext(); )
           if (!anyCondition(it.next()))
              it.remove();
    }
    

    So basic difference between For-Each and iterator is, we can modify collection while iterating using only iterator.

    0 讨论(0)
提交回复
热议问题