xiaolumax

当我们使用for循环删除列表中的数据的时候,会存在问题,因为ArrayList的父类AbstractList里有个modCount的字段记录着List的总数,for循环的时候如果增加或者删除了元素,(修改不会影响),此字段会变化,那么在下次for循环的时候检查到跟之前的长度不同,此时会报ConcurrentModificationException异常。
错误代码:

for (Stuff stuff:mStuffs){
if (stuff.getDelete().equals(true)){
mStuffs.remove(stuff);
}
}
查到一个解决方法23行,我都懒得看
下面是我自己想的解决方法:(大概思想就是直接把不用删除的存到一个List中,最后把原list替换为不用删除的List中)
解决代码:
mStuffList = new ArrayList<>();
for (Stuff stuff:mStuffs){
if (stuff.getDelete().equals(false)){
mStuffList.add(stuff);
}
}
mStuffs.clear();
mStuffs.addAll(mStuffList);
mStuffList.clear();


注:mStuffs是原list,mStuffList是不用删除的list;

本人第一次写博客,写的不好的地方请指出,谢谢!写的不清楚的地方欢迎提问。

相关文章:

  • 2021-10-18
  • 2022-01-04
  • 2021-05-26
  • 2021-08-15
  • 2021-06-01
  • 2021-08-11
  • 2021-10-10
  • 2021-04-10
猜你喜欢
  • 2021-11-01
  • 2021-08-01
  • 2021-12-28
  • 2021-12-26
  • 2021-12-02
  • 2021-04-29
  • 2021-08-20
  • 2021-10-05
相关资源
相似解决方案