modify map while iterating through it
hi all,
i have some java code iam maintaining and am seeing in many places that
HashMap object's iterator is used to iterate and in the loop, the same map is modified (adding an element). is this valid coding? i didnt get any issues so far.
Thanks.
eg code:
for ( Iterator iterator = myHashMap.keySet().iterator(); iterator.hasNext(); )
{
//bla bla bla
myHashMap.put(key,value);
}
iam wondering since the map got modified, how reliable is the iterator used in for loop?
-Madhu
# 2
I have seen comments in Java API that 'removing' an element has to be done by the iterator.. but in my case, iam not removing element, but adding an element into the map.. and the Iterator interface does not have anything to add.
so iam wondering it may be ok to add an element in the loop, but then i should quit the loop...
# 3
You should not add during iteration. If you must, you should add
into a temporary array. When you're done with the iteration,
you can then add everything from the array into the map.
Or, if you quit the iteration right after adding something, that's okay. (That is, if after you add something, you no longer
touch the iterator, then that's okay)
Furthermore:
First of all, you should not use keySet() since it is very inefficient.
You're supposed to use entrySet() instead.
Second of all, if you use entrySet(), then you CAN delete+modify during iteration (just not "add")
for(Iterator i=map.entrySet(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)(i.next());
Object key = e.getKey();
Object value = e.getValue();
// You can now remove this entry like this:
i.remove();
// Or you can alter the value of this entry, like this:
e.setValue(someNewValue);
}