Java Puzzle – For Each Loop
Enhanced version of for loop introduced in JDK 5.0 is for-each. Here is the simple code for traversing a list to search an item and once it finds the item , remove it from list.
1: import java.util.*;2:3: class NewForLoopTest4: {5: public static void main(String[] args)6: {7: ArrayList<String> list = new ArrayList<String>();8: list.add("A1");9: list.add("A2");10: list.add("A3");11: list.add("A4");12: list.add("A5");13: for(String str: list){14: if(str.equals("A2")) {15: list.remove(str);16: System.out.println("A2 found and removed");17: }18: }19: System.out.println("End of Program");20: }21: }
This programs look good and expecting returns list after removing the item.
But the out of this program is :
---------- java ----------
A2 found and removed
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at NewForLoopTest.main(NewForLoopTest.java:13)
Output completed (0 sec consumed)
Why? Here for each loop creates implicit iterator for traversing list and when we are removing list element using list object, it suppose to give Concurrent Modification Exception.
nice
ReplyDelete