Java HashMap删除键/值

Mit*_*uik 16 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();
     }
}
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?

hkn*_*hkn 13

由于您的密钥是String,因此您应该删除String而不是Node.所以试试吧

_adjacentNodes.remove(node.getNodeID());   
Run Code Online (Sandbox Code Playgroud)


Mik*_*wan 8

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 );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将输出以下内容:

Before removal
b
a


After removal
b
Run Code Online (Sandbox Code Playgroud)

我唯一能想到的错误是你在开始时尝试删除的节点对象与你从迭代器获得的节点对象不是同一个节点对象.也就是说,它们具有相同的"NodeID"但是是不同的对象.也许值得你检查remove()的返回值.

编辑:哈,我没有发现字符串/对象的错误,但至少我们走的是正确的道路; )