android移除数据

来源:互联网 发布:小米6陶瓷尊享版 知乎 编辑:程序博客网 时间:2024/05/16 07:26

写项目,经常对list的数据增删改查,今天碰到一个问题,在数量为0的时候需要删除这条数据,直接想到了list.remove();方法。

但是运行的时候发现挂掉了报错:ConcurrentModificationException。

网上查到很多对ConcurrentModificationException异常的解释文章。看完后明白怎么一回事了,是对list的结构进行了修改。

/** 
*在Iterator的内部有个expectedModCount 变量, 
*该变量每次初始化*Iterator的时候等于ArrayList的modCount,modCount记录了对ArrayList的结构修改次数, 
*在通过Iterator对ArrayList进行结构的修改的时候都会将expectedModCount 与modCount同步, 
*但是如果在通过Iterator访问的时候同时又通过索引的方式去修改ArrayList的结构的话, 
*由于通过索引的方式只会修改modCount不会同步修改expectedModCount 就会导致 
*modCount和expectedModCount不相等就会抛ConcurrentModificationException, 
*这也就是Iterator的fail-fast,快速失效的。所以只要采取一种方式操作ArrayList就不会出问题, 
*当然ArrayList不是线程安全的,此处不讨论对线程问题。 

*/

还有一点模糊就是我的项目里只用了索引,是之后改成迭代才解决的问题。

for (ProductUp p : temps) {
           if (list_cxp.size() != 0 && list_cxp != null) {
                    Iterator iterator = list_cxp.iterator();
                     while (iterator.hasNext()) {
                       Product pd = (Product) iterator.next();
                        if (p.getGoods_id().equals(pd.getId())) {
                            iterator.remove();
                           }
                       }
               }
      }

问题是解决了,但还是存在疑问,接着去研究

0 0
原创粉丝点击