如何修复此错误 java.util.ConcurrentModificationException [英] How can I fix this error java.util.ConcurrentModificationException
问题描述
我在以下行中收到错误消息.我正在做添加到 jsonarray 的过程.请帮帮我.
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());
推荐答案
这是我在重新编程时经常遇到的错误.此异常的原因或细节非常清楚.不允许在迭代时修改集合(您正在添加新元素).至少语法 for
不支持这样做.
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).与使用 for
语句循环相比,更好的方法是使用迭代器来避免 ConcurrentModificationException.
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).循环时,不要添加.
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);
这篇关于如何修复此错误 java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!