-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
  • 28,364
  • 7
  • 89
  • 119
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
  • 104,088
  • 27
  • 192
  • 230
0

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

AllTooSir
  • 48,828
  • 16
  • 130
  • 164