HashMap 重复值 - 识别重复值

use*_*948 0 java hashmap duplicates

我知道HashMap不允许插入重复值,它用最新条目替换最后一个重复值。有没有办法打印在该put方法中发现的重复项?

我有以下代码片段:

for( int i = 0; i <= elements.length - 1; i++) {
    nodeDBList = (NodeList) xPath.compile(elements[i]).evaluate(dbDocument, XPathConstants.NODESET);
    for (int j = 0; j < nodeDBList.getLength(); j++) {
        if(nodeDBList.item(j).getFirstChild() != null)
            dbList.put(nodeDBList.item(j).getFirstChild().getNodeValue().toLowerCase().trim(), 
                       nodeDBList.item(j).getNodeName().toLowerCase().trim());

    }
} 
Run Code Online (Sandbox Code Playgroud)

Men*_*ena 5

错误的。HashMap不支持散列的重复键。

对于不同的键,重复值是完全可以接受的。

您可以通过遍历values()方法并使用equals方法来搜索现有值。

编辑

这里的键和值之间似乎存在混淆。

根据's的HashMap实现,该方法将返回给定键的原始值(如果有),或者。Mappublic V put(K key, V value);putnull

来自API 的报价

@return 与 key 关联的先前值,如果没有 key 的映射,则返回 null。(空返回也可以表明映射先前将空与键相关联。)