I created the following code. My objective is to check the use of iterator to remove an element while reading the collection. Can anyone please explain why does a concurrentModificationException is thrown when collection of values of a hashmap is added to a linked list and after creating the iterator for that list, but the same is not thrown when the iterator is obtained after adding the collection to the list?
I know the reason would be very simple and would like something easily available, but yet I just want to confirm what I am thinking is correct or not.
There are 2 other points. 1. As hashmap is not threadsafe, so is it why, that we cant add any element to it while iterator is reading? 2. If yes, then how are we able to remove elements from the map?
package com.Users;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class Temp{
public static void main(String arg[]){
HashMap<String, String> map=new HashMap();
map.put("A", "B");
map.put("C", "D");
LinkedList<String> list=new LinkedList<>();
//****** concurent exception is thrown when ever line 1 is swapped with line 2 ******
Iterator<String> iterator=list.iterator(); //line no. 1
list.addAll(map.values()); //line no. 2
//******************
while(iterator.hasNext()){
if(iterator.next().equals("B")){
iterator.remove();
}
}
System.out.println(list);
}
}