Search code examples
javaexceptionarraysconcurrentmodification

How can I fix this error java.util.ConcurrentModificationException


I get an error on the following line. I'm doing the process of adding to the jsonarray. Please help me.

jsonArr=new JSONArray();
if(req.getSession().getAttribute("userses")!=null){
    String name=(req.getParameter("name")==null?"":to_EnglishName(req.getParameter("name").toUpperCase()));
    if(!name.equals("")){
        for(Book c:GlobalObjects.bookList){
            if(c.getBookName().startsWith(name)){
                    jsonObjec=new JSONObject();
                    jsonObjec.put("label",c.getBookName());
                    jsonObjec.put("value", c.getId());
                    jsonArr.add(jsonObjec);//java.util.ConcurrentModificationException
            }
        }
    }
}
jsonArr.write(res.getWriter());

Solution

  • This is an error I often met while reprogramming. the reason or detail of this exception are pretty clear. it is unallowed to modify the collection(you are adding a new element) while it is being iterated. At least the syntax for DO NOT support do that.

    To fix your problem, there have two way I think it is simple.

    1). rather than using for statement to loop over, the better way is to use iterator to avoid ConcurrentModificationException.

        Iterator<Book> iterator = bookList.iterator();
        while(iterator.hasNext()){
          Book c = iterator.next();
          if(c.getBookName().startsWith(name)){
                    jsonObjec=new JSONObject();
                    jsonObjec.put("label",c.getBookName());
                    jsonObjec.put("value", c.getId());
                    jsonArr.add(jsonObjec);
            }
        }
    

    2). while looping it, don't add it.

         List list = new ArrayList<>();
         for(Book c:GlobalObjects.bookList){
            if(c.getBookName().startsWith(name)){
                    jsonObjec=new JSONObject();
                    jsonObjec.put("label",c.getBookName());
                    jsonObjec.put("value", c.getId());
                    list.add(jsonObjec);//java.util.ConcurrentModificationException
            }
         }
         jsonArr.addAll(list);