java.util.ConcurrentModificationException

本文介绍了一种在处理Java集合时遇到并发修改异常的具体场景,并给出了解决方案。通过使用迭代器移除元素而非直接从循环中删除,避免了异常的发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天出现了没见过的异常,又能get新技能点了。虽然还没解决就开始写博客了,哈哈,因为知道自己一会儿就解决了,边想办法边记录,可能记得清楚点吧,嘿嘿

正文开始

我是在比较两个list集合,一个本地自己记录的userChannelList_my,一个网络请求下来的ChannelList,目的要。。(有点复杂,不说了,反正就是整合一下)。

这是我之前的写法:大致就是对比下如果两个list中bean的Section_Id相同就放到userChannelList中,不同的放到otherChannelList中。

for (SectionInfo.DataBean sectionInfob : userChannelList_my) {
   for (SectionInfo.DataBean sectionInfoa : ChannelList) {
      if (sectionInfoa.getSection_Id().equals(sectionInfob.getSection_Id())) {
         userChannelList.add(sectionInfoa);
         ChannelList.remove(sectionInfoa);
         break;
        }
      }
   }
  otherChannelList.addAll(ChannelList);

现在,需求有变:要根据网络请求下来的ChannelList中bean的Is_Init来区分,就是如果ChannelList中bean的Is_Init为“true”就添加到userChannelList中,而其他的再根据Section_Id是否相同来区分。我的写法变成了这样:

for (SectionInfo.DataBean sectionInfoa : ChannelList) {
     if ("true".equals(sectionInfoa.getIs_Init())) {
          userChannelList.add(sectionInfoa);
          ChannelList.remove(sectionInfoa);
         }else {
             for (SectionInfo.DataBean sectionInfob : userChannelList_my) {
                 if (sectionInfoa.getSection_Id().equals(sectionInfob.getSection_Id())) {
                  userChannelList.add(sectionInfoa);
                  ChannelList.remove(sectionInfoa);
                  break;
                 }
                }
              }
          }
         otherChannelList.addAll(ChannelList);

然后就。。。崩溃了,直接闪退。报错:java.util.ConcurrentModificationException

解决办法

我先查查,还没解决呢,哈哈!
百度了一下,http://www.cnblogs.com/andy-zhou/p/5339683.html这篇文章说:
调用list.remove()方法导致modCount和expectedModCount的值不一致。
注意,像使用for-each进行迭代实际上也会出现这种问题。

然后我修改了下自己的代码:就是把外部for-each换成了迭代器,具体原理详见上面那条连接。

Iterator<SectionInfo.DataBean> iterator = ChannelList.iterator();
while(iterator.hasNext()){
   SectionInfo.DataBean integer = iterator.next();
   if("true".equals(integer.getIs_Init())){
     userChannelList.add(integer);
     iterator.remove();   //注意这个地方
     }else{
          for (SectionInfo.DataBean sectionInfob : userChannelList_my) {
              if (integer.getSection_Id().equals(sectionInfob.getSection_Id())) {
                 userChannelList.add(integer);
                 ChannelList.remove(integer);
                 break;
                }
           }
      }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值