2

I have following code -

import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("1a");
        list.add("2b");
        for (String s : list) {
            list.remove(s);
        }
        System.out.println("Removed");
        System.out.println(list);

    }

}

If I run this program, I expect it should throw exception but the output is "2b". If it is running fine then why It is not removing the last object.

Again If I add more element in the list It is thorwing exception java.util.ConcurrentModificationException Which is expected.

My question is -

  1. Why it is not removing all the elements from list if we have 2 elements in the list ??
  2. Why the java.util.ConcurrentModificationException exception occur only when we have more elements ?? I tried a lot of time with two elements.

I am using Java 8.

Thanks in advance.

Menelaos Kotsollaris
  • 5,776
  • 9
  • 54
  • 68
Rakesh Chouhan
  • 1,196
  • 12
  • 28
  • What do you mean in your second question? More elements than how much? – Menelaos Kotsollaris Apr 29 '15 at 11:23
  • 1
    Please refer to this question http://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java There many great answers and comments about your 2 questions – JuniorDev Apr 29 '15 at 11:24
  • It is different from the post which you have given, I have two questions here why It is not removing all the elements from the list if we have only 2 elements. – Rakesh Chouhan Apr 29 '15 at 11:40
  • You can check the source code of arraylist to see how it behaves. In the same spirit of your question, check http://stackoverflow.com/questions/24556487/it-does-not-throw-exception-concurrentmodificationexception – Alexis C. Apr 29 '15 at 12:16

1 Answers1

2

Actually, when you are removing 1a from the list, the size is getting reduced, and you now have only 1 element in the list, thus the loop does not execute the second time, there by resulting in the keeping the second element.

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57