-2

I need to delete some objects from a list if they meet a condition.

But I am getting java.util.ConcurrentModificationException.

Here is my code:

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

for(College clg:collegeList){
    if(!clg.approve()){
        collegeList.remove(clg);
    }
}
Richard JP Le Guen
  • 27,705
  • 7
  • 87
  • 116
rashi
  • 13
  • 1
  • 3
  • You need to use an iterator here – Arun P Johny Jun 28 '13 at 05:45
  • 3
    @ruchi Just take some time and effort to search SO before you post such questions. There are plenty of good answers to that on SO already - For e.g. - [here](http://stackoverflow.com/questions/223918/efficient-equivalent-for-removing-elements-while-iterating-the-collection?rq=1) – rtindru Jun 28 '13 at 05:48

2 Answers2

10

You can't remove elements while iterating through them in that manner. Use an Iterator instead.

Iterator<College> iter = collegeList.iterator();
while(iter.hasNext()) {
    College clg = iter.next();
    if(!clg.approve()) {
        iter.remove();
    }
}
Makoto
  • 100,191
  • 27
  • 181
  • 221
0

You need to use an Iterator to iterate through List and remove objects using Iterator#remove().

AllTooSir
  • 47,910
  • 16
  • 124
  • 159