我如何解决这个错误java.util.ConcurrentModificationException [英] How can I fix this error java.util.ConcurrentModificationException

查看:1017
本文介绍了我如何解决这个错误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());


推荐答案

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

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)。而不是使用语句中的循环,更好的方法是使用迭代器来避免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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆