简体   繁体   English

Java HashMap删除键/值

[英]Java HashMap Removing Key/Value

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? 到底是怎么回事?

Since your key is a String you should remove String not Node. 由于您的密钥是String,因此您应该删除String而不是Node。 So try 所以试试吧

_adjacentNodes.remove(node.getNodeID());   

remove() does work as expected. remove()确实按预期工作。 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. 也就是说,它们具有相同的“NodeID”但是是不同的对象。 Perhaps it is worth it for you to check the return of remove(). 也许值得你检查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). 这里的要点是,如果你在遍历hashmap然后尝试操作它,它将失败,因为你不能这样做(甚至有一个例外)。

So you need to use an iterator to remove an item on the very list you are iterating over. 因此,您需要使用迭代器来删除正在迭代的列表中的项目。

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

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