Reputation: 193
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?
Upvotes: 17
Views: 92010
Reputation: 105
The point here is that if you are iterating over the hashmap and then trying to manipulate it, it will fail because you cannot do that (there is even an exception for that).
So you need to use an iterator to remove an item on the very list you are iterating over.
Upvotes: 0
Reputation: 24447
remove() does work as expected. For example given this program:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
System.out.println("Before removal");
for( String s : map.keySet() ) {
System.out.println( s );
}
System.out.println("\n\nAfter removal");
map.remove("a");
for( String s : map.keySet() ) {
System.out.println( s );
}
}
}
This will output the following:
Before removal
b
a
After removal
b
The only thing I can think of which is going wrong is that the node object you are trying to remove at the start is not the same node object as the one you get from the iterator. That is, they have the same 'NodeID' but are different objects. Perhaps it is worth it for you to check the return of remove().
Edit: Ha I didn't spot the String/Object mistake but at least we were going down the right path ; )
Upvotes: 9
Reputation: 1448
Since your key is a String you should remove String not Node. So try
_adjacentNodes.remove(node.getNodeID());
Upvotes: 14