- Home /
hashtable: snapshot out of sync
Hi, Im trying to create a tree-structure and am trying to delete some elements from the tree. I dont quite understand why the MyHashTable.Remove(#key) is causing this exepction:
InvalidOperationException: Hashtable.Enumerator: snapshot out of sync. System.Collections.Hashtable + Enumerator.FailFast()
the key does not have to be a string if i read it correctly? Im using ints as keys.
protected var idListe : Hashtable = new Hashtable();
public function remove(nodeId:int){ var startId = idListe[nodeId].getIdLeft(); var targetId = idListe[nodeId].getIdRight(); var endId = idListe[0].getIdRight();
for (var item : DictionaryEntry in idListe){
var id:int = item.Value.getId();
var idLeft:int = item.Value.getIdLeft();
var idRight:int = item.Value.getIdRight();
Debug.Log("Checking (" + nodeId + "):"+id+" => " +idLeft + " >= " + startId + " && " +idRight + " <= " + targetId);
if (idLeft >= startId && idRight <= targetId){
Debug.Log("Deleting:"+id);
idListe.Remove(id);
}
}
updateIdListe(startId ,endId,(targetId-startId));
}
Answer by noony · Jun 01, 2010 at 04:27 PM
This exception is being generated because you're removing items from idListe
while you're iterating through it. Using a foreach
-style loop as you have will only allow you to read the collection, but not modify it in any way.
The easiest way around this would be to assemble a temporary copy of the hashtable as you iterate through it, keeping the items that you require, then copy it back to idListe
when you're finished.
Answer by Ent · Jun 01, 2010 at 04:27 PM
I worked it out myself :)
the reference to the Hashtable in the for loop is still pointing to the current hash entry. If I remove the current index, the current for pointer seems to be pointing to nothing and therefore the hashtable is out of sync. So I need to make a list of elements to delete in the the for loop and delete them after the for loop seperately.