Is following code the safe way to remove a element in the Hashtable?
Enumeration keys = siCache.keys(); //siCache is Hashtable
while(keys.hasMoreElements())
{
String k = (String) keys.nextElement();
Object v = siCache.get(k);
if(condition) siCache.remove(k);
}
Removing an element from a
Hashtablewhile enumerating the keys is potentially risky. Here’s what the javadoc says:The implication is clear: arbitrary, non-deterministic behaviour is possible if you do that.
Solutions:
keySet(). Or better still, don’t UseHashtable.