今天在做项目时,需要删除list和set中的某些元素,当时使用边遍历,边删除的方法,却报了以下异常:
concurrentmodificationexception
为了以后不忘记,使用烂笔头把它记录如下:
错误代码的写法,也就是报出上面异常的写法:
set<checkwork> set = this.getuserdao().getall(qf).get(0).getactioncheckworks(); for(checkwork checkwork : set){ if(checkwork.getstate()==1){ set.remove(checkwork); } }
注意:使用上面的写法就会报上面的concurrenmodificationexception异常,原因是,集合不可以一边遍历一边删除。
正确的写法如下:
1. 遍历删除list
list<checkwork> list = this.getuserdao().getall(); iterator<checkwork> chk_it = list.iterator(); while(chk_it.hasnext()){ checkwork checkwork = chk_it.next(); if(checkwork.getplanstate()==1){ chk_it.remove(); } }
2. 遍历删除set
set<checkwork> set = this.getuserdao().getall().get(0).getactioncheckworks(); iterator<checkwork> it = set.iterator(); while(it.hasnext()){ checkwork checkwork = it.next(); if(checkwork.getstate()==1){ it.remove(); } }
以上这篇java中循环遍历删除list和set集合中元素的方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
《UnityAPI.Collision碰撞》(Yanlz+Unity+SteamVR+云技术+5G+AI+VR云游戏+Collision+collider+rigidbody+立钻哥哥++OK++)
荐 2020年Java面试上必问的26个高频关键知识点,刷三遍必进阿里腾讯大厂!就这么自信!
使用IDEA搭建Springboot项目(dao层使用Mybatis)
网友评论