Java HashMap 删除键/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6531132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java HashMap Removing Key/Value
提问by Mitchell Romanuik
I'm just looking for an explanation and/or insight as to why its better to iterate over a HashMap.
我只是在寻找关于为什么迭代 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.
例如,下面的代码(在我看来)完全相同(或者应该这样做)。但是,如果我不遍历 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();
}
}
What is going on?
到底是怎么回事?
采纳答案by hkn
Since your key is a String you should remove String not Node. So try
由于您的键是一个字符串,您应该删除字符串而不是节点。所以试试
_adjacentNodes.remove(node.getNodeID());
回答by Mike Kwan
remove() does work as expected. For example given this program:
remove() 确实按预期工作。例如给出这个程序:
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().
我能想到的唯一错误是您在开始时尝试删除的节点对象与您从迭代器中获得的节点对象不同。也就是说,它们具有相同的“NodeID”但是是不同的对象。也许检查 remove() 的返回值对您来说是值得的。
Edit: Ha I didn't spot the String/Object mistake but at least we were going down the right path ; )
编辑:哈我没有发现字符串/对象错误,但至少我们走在正确的道路上;)
回答by comrad
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.
因此,您需要使用迭代器来删除您正在迭代的列表中的项目。