Java中的HashMap不起作用?

jer*_*jtu 1 java hashmap

这是我的代码:

double getRevenue(KeywordGroupKey key) {
    Double r = revenueMap.get(key);
    System.out.println(key + "\t" + key.hashCode());
    for (KeywordGroupKey other : revenueMap.keySet()) {
        System.out.println(other.toString() + "\t" + other.hashCode());
        if(other.equals(key))
            System.out.println("equals here...");
    }
    if(r == null)
        r = 0.0;
    return r;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

????????|"???"  955095524
brand+????|???? 726983298
brand-?????|??????  -713384514
brand-???|???   2029153675
brand+????|?????    261410621
????????|"???"  955095524
equals here...
Run Code Online (Sandbox Code Playgroud)

所以这个方法返回的值是空的很奇怪,为什么会发生这种情况呢?由于在revenueMap中有一个键具有相同的哈希码并且与参数键相等.以下是revenueMap和key的当前状态:

{brand+????|????=28.0, brand-?????|??????=49.9, brand-???|???=21.0, brand+????|?????=167.0, ????????|"???"=9.9}
????????|"???"
Run Code Online (Sandbox Code Playgroud)

Joa*_*uer 7

我的猜测是它KeywordGroupKey是可变的,并且在将它用作哈希映射的关键字之后修改了有问题的密钥.

如果是这种情况,则密钥位于错误的"桶"中HashMap,get()方法(或containsKey()方法)将永远不会找到它(但是迭代密钥和/或条目找到它!).

例如,假设foo您的类中有属性,并且该属性与您hashCode()equals()方法相关.以下代码将"破坏" HashMap:

KeywordGroupKey key = ...
revenueMap.put(key, someValue);
key.setFoo("differentValue");
Double result = revenueMap.get(key); // will return nothing!
Double result = revenueMap.get(originalValueOfKey); // will *also* return nothing!
Run Code Online (Sandbox Code Playgroud)

  • 我说你在'HashMap`中插入的键在**之后用*作为地图中的键来改变***,这会"破坏"地图. (2认同)