gpt4 book ai didi

java - 为什么containsKey没有找到key?

转载 作者:行者123 更新时间:2023-11-29 09:46:18 26 4
gpt4 key购买 nike

我有以下代码:

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

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

我仍然对 key 有疑问。以下代码表示每次我添加一个 key 时我都会添加一个新 key 。我知道事实并非如此。

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

最佳答案

您正在使用 Integer[] 作为 map 中的键。这是一件坏事,因为 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.如果您认为有道理,请点

关于java - 为什么containsKey没有找到key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4410498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com