从列表中删除某些对象时出现"java.util.ConcurrentModificationException"

-2 java

如果符合条件,我需要从列表中删除一些对象.

但我得到了java.util.ConcurrentModificationException.

这是我的代码:

collegeList.addAll(CollegeManager.findByCollegeID(stateCode, districtCode));

for(College clg:collegeList){
    if(!clg.approve()){
        collegeList.remove(clg);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mak*_*oto 11

以这种方式迭代元素时,不能删除元素.请Iterator改用.

Iterator<College> iter = collegeList.iterator();
while(iter.hasNext()) {
    College clg = iter.next();
    if(!clg.approve()) {
        iter.remove();
    }
}
Run Code Online (Sandbox Code Playgroud)