While I was testing my own answer to get the output for this question, I got the following output for the given list content:
// Add some strings into the list
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
Output:
Item 1
Item 2
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at com.akefirad.tests.Main$1.run(Main.java:34)
at java.lang.Thread.run(Thread.java:745)
But if one use the following list:
// Add some strings into the list
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
Output:
Item 1
Item 2
There is no exception in the output and only two first items will be printed. Can anyone explain why it behaves like this? Thanks
Note: the code is here.
EDITED: My question is why I don't have the third item printed (meaning the list is modified) and while there is no exception.
EDITED the code to produce the exception, please note the list content:
public class Main {
public static void main(String[] args) throws InterruptedException
{
final ArrayList<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
Thread thread = new Thread(new Runnable()
{
@Override
public void run ()
{
for (String s : list)
{
System.out.println(s);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
});
thread.start();
Thread.sleep(2000);
list.remove(0);
}
}