java.util.concurrentModification Exception while Iteration over JSONObject

Question

I've this following code chunk using which i want to store the value in JSONObject in order to iterate over it and render it over front end.

        JSONObject dlCovs = jsonObject.getJSONObject("result").getJSONObject("cov_details");
        Iterator x = dlCovs.keys();
        while (x.hasNext()){
            String key1 = (String) x.next();
            String value1 = dlCovs.optString(key1);
            dlCovs.put("covabbrv",key1);
            dlCovs.put("dcIssuedt",value1);
            dlCovs.put("vecatg",key1);
            dlData.put("dlCovs", dlCovs);
        }

       /* dlCovs.put("covabbrv",cov);
        dlCovs.put("issue_date",issue_date);*/
        dlObj.put("status","valid");
        dlData.put("dlCovs", dlCovs);
        dlData.put("status","valid");

while iterating over the data in while loop i'm getting java.util.concurrentModificationException, their is also a case when i'm trying to debug it it is storing the value in dlData.put("dlCovs",dlCovs), but as soon as it's coming for iteration for the second time it throws error. I've following JSON value

 "cov_details": {
     "MCWG": "NA",
     "3WTR": "NA",
     "PSV BUS": "NA",
     "LMV": "NA",
     "INVCRG": "NA"
 },

Any help will be highly appreciable,thanks well in advance enter code here


Show source
| java   | json   2017-01-03 13:01 2 Answers

Answers ( 2 )

  1. 2017-01-03 13:01

    You're modifying the map whilst iterating its entries. You can't do that.

    Put the items into a separate map, then add that to your "main" map afterwards:

      Map newEntries = new HashMap();
      Iterator x = dlCovs.keys();
      while (x.hasNext()){
        String key1 = (String) x.next();
        String value1 = dlCovs.optString(key1);
        newEntries.put("covabbrv",key1);
        // .. etc
      }
    
      dlCovs.putAll(newEntries);
    

    Also: don't use raw types. You should be declaring x like:

    Iterator<String> x = dlCovs.keys();
    

    then you don't need the cast:

    String key1 = x.next();
    

    Similarly:

    Map<String, String> newEntries = new HashMap<>();
    
  2. 2017-01-03 14:01

    While iterating over maps using an iterator you cannot change the underlying map. It is called a Fail fast iterator which reads directly from the underlying structure. Java maintains an internal flag called mods which counts the number of structural changes made to the map. If the iterator finds mods to change while it is iterating, then it throws a Concurrent Modification Exception. In Java concurrent hash maps do solve the problem by implementing fail safe iterators. Main thing is you cannot change the structure of map while iterating

◀ Go back