LinkedHashMap insertion whilst iterating
I wrote a class with a LinkedHashMap that I iterate over whilst inserting new elements. Here is a simplified example:
Code:
LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
map.put(666, "test");
System.out.println(iterator.hasNext());
The result is: false. If you swap the 2nd and 3rd lines though, its true.
I did an experiment with LinkedList and the problem does not occur here; the result is true whether the iterator was created before or after the call to put.
Perhaps the entrySet() method gets a copy of the data, as it is at that time. so when you add new data its result is unaffected.
So, it looks like I am going to have to use another data structure!