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 surprised and had question in mind how all these for each loop works.
Example (sample program),

```
public static void main( String[] args )
{
    String myInput = "hello , hi , how are you ";
    String[] splitted = myInput.split(",");
    List<String> mylist = new ArrayList<String>();
    for (String output : splitted) 
    {
        mylist.add(output);
    }

    for (String output : mylist) 
    {
        System.out.println(output);
        mylist = new ArrayList<String>(); //It worked 
        mylist.add(output);
    }

    for (String output : splitted) 
    {
        mylist.add(output);
    }

    for (String output : mylist) 
    {
        System.out.println(output);             
        mylist.add(output); // After this line it threw exception java.util.ConcurrentModificationException
    }

}

```

I was curious to know and while searching I found one more post that said we can remove elements from list if we used iterator approach, So I tried,

```
for (String output : splitted) 
{
    mylist.add(output);
}
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.
}

```

Now I just want to know what is happening behind the every for each loop quoted above.  

**I want to know the technical aspect, I know I can not modify the collection in for each loop but in some case stated above it worked why?**