Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap Removing Key/Value

Tags:

java

hashmap

I'm just looking for an explanation and/or insight as to why its better to iterate over a HashMap.

For instance the code below (in my eyes) does the exact same (or it should). However if I don't iterate over the HashMap the key is not removed.

_adjacentNodes.remove(node);        

Iterator<Map.Entry<String, LinkedList<Node>>> iterator = _adjacentNodes.entrySet().iterator();
while (iterator.hasNext()) {
     Map.Entry<String, LinkedList<Node>> entry = iterator.next();
     if(node.getNodeID().contentEquals(entry.getKey())){
          iterator.remove();
     }
}

What is going on?

like image 909
Mitchell Romanuik Avatar asked Jun 30 '11 07:06

Mitchell Romanuik


1 Answers

Since your key is a String you should remove String not Node. So try

_adjacentNodes.remove(node.getNodeID());   
like image 72
hkn Avatar answered Sep 25 '22 13:09

hkn