如何解决此错误java.util.ConcurrentModificationException

ali*_*ane 5 java arrays exception concurrentmodification

我在下一行收到错误.我正在做添加到jsonarray的过程.请帮我.

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());
Run Code Online (Sandbox Code Playgroud)

C.c*_*C.c 14

这是我在重新编程时经常遇到的错误.这个例外的原因或细节非常清楚.在迭代时不允许修改集合(您正在添加新元素).至少语法for不支持这样做.

为了解决您的问题,我认为有两种方法很简单.

1).而不是使用for语句循环,更好的方法是使用迭代器来避免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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

2).循环时,不要添加它.

     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);
Run Code Online (Sandbox Code Playgroud)