of recommends looping through the removal of elements from the List and Set collections
- 2020-05-19 04:45:42
- OfStack
When I was working on the project today, I needed to delete some elements in List and Set. When I used the method of edge traversal and edge deletion, the following exception was reported:
ConcurrentModificationException
In order not to forget it in the future, use a rotten pen to record it as follows:
The way the error code is written, that is, the way the above exception is written:
Set<CheckWork> set = this.getUserDao().getAll(qf).get(0).getActionCheckWorks();
for(CheckWork checkWork : set){
if(checkWork.getState()==1){
set.remove(checkWork);
}
}
Note: using the above method will result in an ConcurrenModificationException exception in the newspaper. The reason is that a collection cannot be deleted by one side traversing one side.
The correct way to write it is as follows:
1. Traverse to delete 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. Traverse to delete 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();
}
}