今天出现了没见过的异常,又能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;
}
}
}
}