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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…