exception - How can I fix this error java.util.ConcurrentModificationException -


I get an error on the following line I am processing to add jsonarray Please help me jsonArr = New JSONArray (); If (req.getSession (). GetAttribute ("userses") = null) {string name = (req.getParameter ("name") == empty? "": To_EnglishName (req.getParameter ("name"). ToUpperCase ))); If (! Name.equals ("")) {for (book c: GlobalObjects.bookList) {if (c.getBookName (). Begin (with name)) {jsonObjec = new JSONObject (); JsonObjec.put ("label", c.getBookName ()); JsonObjec.put ("value", c.getId ()); JsonArr.add (jsonObjec); // java.util.ConcurrentModificationException}}}} jsonArr.write (res.getWriter ());

This is an error that I often found during reprogramming. Due to this exception or the description is very clear it is rejected to modify the collection (you are adding a new element) while it is being weighted for at least the syntax for do not do this

To fix your problem, there are two ways I think it is simple.

1). Rather than using the for statement above the loop, using Iterator is a good way to avoid concurrent improvements.

  Iterator & lt; Book & gt; Iterator = bookList.iterator (); While (iterator.hasNext ()) {book c = iterator.next (); If (c.getBookName (). BeginWith (name) {jsonObjec = new JSONObject (); JsonObjec.put ("label", c.getBookName ()); JsonObjec.put ("value", c.getId ()); JsonArr.add (jsonObjec); }}   

2). While looping it, do not add it.

  list list = new alright & lt; & Gt; (); (Book c: GlobalObjects.bookList) {if (c.getBookName (). BeginWith (name)} {jsonObjec = new JSONObject (); JsonObjec.put ("label", c.getBookName ()); JsonObjec.put ("value", c.getId ()); List.add (jsonObjec); // java.util.ConcurrentModificationException}} jsonArr.addAll (list);    

Comments