0

Below mentioned code is not throwing ConcurrentModificationException.

List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(String s : list){
    if(list.get(3).equals(s)){
        list.remove(3);
    }
}

Why it is so?????? If i change the if condition to list.get(x).equals(s), where x is anything apart from list.size()-1, than getting ConcurrentModificationException.

After changing the code to below getting ConcurrentModificationException

    List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    for(String s : list){
        if(list.get(2).equals(s)){
            list.remove(3);
        }
    }

Edit 2

I am also getting ConcurrentModification in this case also. As per the answer provided that on check of hasNext() we call next() which can throw exception. But as here we are removing last element so there is not any chance that hasNext() will pass. Than why exception ????

    List<String> list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    for(String s : list){
        if(list.get(4).equals(s)){
            list.remove(0);
        }
    }
Mayank Gupta
  • 93
  • 1
  • 11
  • 2
    this is not a duplicate. in fact it i the poster is questioning why he isn't getting the expected behavior – MeBigFatGuy Sep 29 '16 at 19:41
  • @Tunaki : It is not a duplicate one a you mentioned, as i am asking why i am not getting ConcurrentModificationException. – Mayank Gupta Sep 29 '16 at 19:55
  • @MeBigFatGuy From the linked question _I don't understand why the List.remove in main method throws ConcurrentModificationException **but not in the remove method**._ This is a duplicate because it explicitely asks why they are NOT getting the exception. And the explanation is exactly the same. – Tunaki Sep 29 '16 at 19:57
  • 1
    @Tunaki : Thanks tunaki, it seems clear to me now. – Mayank Gupta Sep 29 '16 at 20:20
  • @Tunaki : have added one more piece of code snippet. Can you please have a look. – Mayank Gupta Sep 29 '16 at 20:27
  • 1
    Actually, `hasNext()` does pass in your last example, because, at the last iteration, one element was removed, and then it detects that you want the 6th element (`cursor = 5`). But the list now has a size of 4. As `hasNext()` checks for `cursor != size`, not less than or greater than, it returns `true`, so `next()` is called and the exception happens. You can step through the code in debug mode to see it happen in action. This peculiarity only happens when you remove an element when the iteration is at the second to last element, because then, after the removal, you have `cursor == size`. – Tunaki Sep 29 '16 at 20:39
  • @Tunaki: ok got it. But it is miss from java side than, it should be less than(curosr < size). Bdw thanks. – Mayank Gupta Sep 30 '16 at 07:14

0 Answers0