为什么containsKey没找到钥匙?

时间:2010-12-10 15:41:45

标签: java map key hashmap containskey

我有以下代码:

payoffs2exchanges.put(point, exchange);
if (!payoffs2exchanges.containsKey(point) ) {
   game.log.fine("yes");
} else {
   game.log.fine("no");
}

输出“否”。换句话说,我将键值对添加到地图中,然后,在此之后我立即检查密钥是否存在并发现它不存在。为什么?

我仍然遇到钥匙的问题。以下代码说每次添加密钥时我都会添加一个新密钥。我知道事实并非如此。

        Integer[] point = new Integer[2];
        point[0] = proposerBestScore;
        point[1] = responderBestScore;
        game.log.fine("In the getCloudOfPayoffs: found payoffs:" + point[0] + "," + point[1] + ". Exchange: " + exchange[0]+","+exchange[1]+","+exchange[2]+","+exchange[3]+","+exchange[4]);
        // With the following block we ensure that every options (pair of payoffs) is represented by exchange with minimal number of moves.
        if (!payoffs2exchanges.containsKey(point)) {
            payoffs2exchanges.put(point, exchange); 
            game.log.fine("In the getCloudOfPayoffs: this option is new. We add it to the map.");
        } else {
            game.log.fine("In the getCloudOfPayoffs: this option is old.");
            Integer[] exchangeFromMap = payoffs2exchanges.get(point);
            Integer newSum = 0;
            Integer oldSum = 0;
            for (int i=0;i<Design.nColors;i++) {
                newSum = newSum + Math.abs(exchange[i]);
                oldSum = oldSum + Math.abs(exchangeFromMap[i]);
            }
            if (newSum<oldSum) {
                game.log.fine("In the getCloudOfPayoffs: the new exchange is better than the old one.");
                payoffs2exchanges.put(point, exchange);
            }
        }

3 个答案:

答案 0 :(得分:6)

做正确的事。 containsKey返回true!运算符将其否定为false,因此输出no(else子句)。

答案 1 :(得分:6)

您在地图中使用Integer[]作为关键字。这是一件坏事,因为 Java数组没有像您期望的那样实现equalshashCode请参阅此示例:

public class Test {
    public static void main(String[] args) {
        Integer[] arr1 = { 1, 2 };
        Integer[] arr2 = { 1, 2 };

        System.out.println(arr1.equals(arr2));
        System.out.println(arr1.hashCode() + " / " + arr2.hashCode());
    }
}

在我的电脑上打印:

false
1476323068 / 535746438

我的建议是创建一个自定义Point类,正确覆盖equalshashCode(如果您认为有意义,可以重用java.awt.Point

答案 2 :(得分:0)

查看你的代码:)如果地图实际上包含密钥,则打印no