繁体   English   中英

Java HashMap删除键/值

[英]Java HashMap Removing Key/Value

我只是在寻找解释和/或洞察为什么更好地迭代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();
     }
}

到底是怎么回事?

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

_adjacentNodes.remove(node.getNodeID());   

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 );
        }
    }
}

这将输出以下内容:

Before removal
b
a


After removal
b

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

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

这里的要点是,如果你在遍历hashmap然后尝试操作它,它将失败,因为你不能这样做(甚至有一个例外)。

因此,您需要使用迭代器来删除正在迭代的列表中的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM