2010-12-10 45 views
1

我有以下代码:为什么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); 
      } 
     } 
+0

什么类是'point'?定制课程? 'payoffs2exchanges'是什么类? – 2010-12-10 15:44:16

+0

添加了一个解答您的更新的答案。 – aioobe 2010-12-10 16:02:52

+0

@aioobe,抱歉对这些问题的操作。我把它放回去了。所以,你的回答很有用。 – Roman 2010-12-10 16:07:24

回答

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如果你认为品牌感)。

+0

是否意味着containsKey不起作用,如果我使用整数数组作为关键? – Roman 2010-12-10 16:06:35

+0

是的,确切地说。一般来说,地图很大程度上依赖于equals方法,而当涉及到例如'HashMap'时,'hashCode'也很重要。 – aioobe 2010-12-10 16:07:32

+0

但我仍然可以使用'somHashMap.get(key)'如果key是一个整型数组? – Roman 2010-12-10 16:09:59

6

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

+0

谢谢!这是一个愚蠢的问题。 – Roman 2010-12-10 15:47:10

+0

欢迎。我想这是一个粗心的错误。 – lijie 2010-12-10 15:53:01

0

看看你的代码:)它打印no如果映射实际上包含的关键...