0
public static void main(String[] args) {    
    List<String> list = new ArrayList<String>(); 
    list.add("Value1"); 
    list.add("Value2"); 
    list.add("Value3"); 

    for(String val: list ) {  
        list.remove(0);     
        System.out.println(list); 
    } 
}

o\p: [Value2, Value3] Exception in thread "main" java.util.ConcurrentModificationException

Here I am trying to read and remove the 0th element concurrently. So It should give an exception.But My qn is why does it execute the println statements after the exception.The moment it finds the exception it should come out of the loop.

Chris
  • 20,138
  • 2
  • 29
  • 43
niharr7
  • 41
  • 1
  • 11
  • possible duplicate of [ConcurrentModificationException?](http://stackoverflow.com/questions/15444391/concurrentmodificationexception) – arghtype Aug 21 '14 at 07:33
  • You have the thread dump which should show the stack trace and give you the exact line number the exception is thrown from. Check that the exception isn't being thrown from the second time through the FOR statement, when it attempts to get the next value from the list. The remove operation knows nothing about the iterator, but the iterator can know something has changed in the list. – Chris Aug 21 '14 at 14:12

3 Answers3

1

You should not use a for-loop here. Use an iterator which will not lead to an Exception:

ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
    String string = iterator.next();
    iterator.remove();
}
Deutro
  • 3,113
  • 4
  • 18
  • 26
  • Yes,The exception is fine.But My qn is why does it execute the println statements after the exception.The moment it finds the exception it should come out of the loop. – niharr7 Aug 25 '14 at 05:52
0

Becasue you are using a for-each loop it is throwinng this beacsue when you remove from an arraylist the things shift back so you are skipping over one Hence. To fix this use a regualr for loop;

for(int i=0;i<list.size();i++){
  list.remove(i);
   i--;
   System.out.print(i);
}
rush2sk8
  • 362
  • 6
  • 16
0

you can use get Iterator and iterator.remove()

How Iterator's remove method actually remove an object

Community
  • 1
  • 1
Kalpesh Soni
  • 6,879
  • 2
  • 56
  • 59