2010-12-10 124 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如果映射實際上包含的關鍵...