I was working on certain task, when incidentally did something wrong according to me but the code executed and provided correct result. I was little surpris
for-each loop of List will be internally converted to for loop with iterator.
for (String output : mylist)
{
System.out.println(output);
mylist = new ArrayList(); //It worked
mylist.add(output);
}
gets converted to
for (Iterator iterator = mylist.iterator(); iterator.hasNext();) {
String output = (String)iterator.next();
System.out.println(output);
mylist = new ArrayList(); //It worked
mylist.add(output);
}
And since the the snapshot of list is already taken at below
for (Iterator iterator = mylist.iterator(); iterator.hasNext();) {
The loop is running until the last element of list i.e. "how are you".
Whereas, below is not working because of FailFast behaviour of List.
for (String output : mylist)
{
System.out.println(output);
mylist.add(output); // After this line it threw exception java.util.ConcurrentModificationException
}
It says, if you are modifying the list while iterating, with anything other than iterator's own remove method, List will throw ConcurrentModificationException and thats the reason the below is working.
for (Iterator iterator2 = mylist.iterator(); iterator2.hasNext();)
{
String string = (String) iterator2.next();
System.out.println(string);
iterator2.remove(); //It worked but if I used the same thing to remove element from original list it threw exception.
}