When working on a project today, you need to delete some elements in List and Set. When using the method of traversing and deleting while using the following exception:
ConcurrentModificationException
In order not to forget it in the future, use a bad pen tip to record it as follows:
The way to write the error code, that is, the way to write the above exception:
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 writing method will report the above ConcurrenModificationException exception. The reason is that the collection cannot be deleted while traversing.
The correct way to write it is as follows:
1. Traversal and 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. Traversal and 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();}}The above method of traversing and deleting elements in List and Set collections in Java (recommended) is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.