0

removeIndex=0

for (Demo demo: demo1) {​​
  if ( demo..getSudentInfoInfo().getRollId()>2) {​​
    demo.remove(removeIndex);
  }​​
  removeIndex++;
}

I am getting exception at first line of my code, i have custom arraylist of object , i am trying to accessing method through variable demo.

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
Abhas Jain
  • 11
  • 2
  • You cannot remove elements from a collection you are iterating over – Simon Martinelli Mar 03 '21 at 16:26
  • Does this answer your question? [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Giorgi Tsiklauri Mar 03 '21 at 16:39

2 Answers2

0

You cannot remove elements from a collection you are iterating over. You can use an Iterator:

Iterator i = demo1.iterator();
while (i.hasNext()) {
    if (demo.getSudentInfoInfo().getRollId() > 2) {​​
      i.remove();
    }​​
}
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • Even though this answers the question, I think this still lacks the point of explanation. It shouldn't be just to make something work.. but also, explain - *why*s. Only "you cannot do that" is not so helpful. Also, Iterator is a generic type.. and using raw variant, is not best.. it would result in getting Objects with .`next()`. – Giorgi Tsiklauri Mar 03 '21 at 16:41
0

To add onto Simon’s point, the same exception would be thrown when using the forEach method and attempting to remove from the list

J.Correa
  • 11
  • 4