Java HashMap 删除键/值
我只是在寻找关于为什么最好迭代 HashMap 的解释和/或见解。
例如,下面的代码(在我看来)的作用完全相同(或者应该如此)。但是,如果我不迭代 HashMap,则不会删除键。
_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();
}
}
到底是怎么回事?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您的键是字符串,因此您应该删除字符串而不是节点。所以尝试一下
Since your key is a String you should remove String not Node. So try
remove() 确实按预期工作。例如,给定这个程序:
这将输出以下内容:
我能想到的唯一出错的事情是您试图在开始时删除的节点对象与您从迭代器获得的节点对象不是同一节点对象。也就是说,它们具有相同的“NodeID”,但是不同的对象。也许您值得检查一下remove()的返回值。
编辑:哈,我没有发现字符串/对象错误,但至少我们走在正确的道路上; )
remove() does work as expected. For example given this program:
This will output the following:
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 ; )
这里的要点是,如果您迭代哈希图然后尝试操作它,它将失败,因为您无法做到这一点(甚至有一个例外)。
因此,您需要使用迭代器来删除您正在迭代的列表上的项目。
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.