2014-08-27 74 views
0

對不起,如果標題沒有足夠的解釋,因爲我是相當新的。爲什麼我的Hashmap沒有註冊(工作)

只是發生了什麼是我想註冊一個配方(見下面的代碼)。然後我想檢查輸入配方是否與註冊配方匹配。我通過hashmaps和數組來做這件事。

public static Integer CraftRecipe(int item1, int item2, int item3, int item4, int item5, int item6){ 

    int[] recipeFormatter = new int[]{item1, item2, item3, item4, item5, item6}; 
    int[] recipeInput = recipeFormatter;   
    Recipe.put(recipeInput, 7); 

    if (Recipe.containsKey(recipeInput)){ 
     System.out.println("Recipe Worked"); 
     return Recipe.get(recipeInput); 
    } else {    
     System.out.println("Recipe Failed");    
     return null;    
    }  
} 

所以我的問題是註冊的配方沒有出現,當我測試它。我在做hashmaps,數組方法有問題嗎?如果有的話,我怎麼能達到我想要的結果?

+0

什麼是食譜的類型?你能發佈它的源代碼嗎? – nogard 2014-08-27 16:08:26

+2

是的。不要將直接數組存儲在Map中(一般情況下)。 – 2014-08-27 16:08:37

回答

2

因爲數組不會覆蓋hashCode也不equals方法不使用陣列(Object[]int[]或其他)作爲鍵您Map

如果使用數組作爲你的密鑰,使用List相反,通過使用Arrays#asList容易實現。但是對於原始類型的數組而言,這會降低,因爲這種方法會將它們威脅爲單個Object。在代碼:

int[] fooArray = { 1, 2, 3 }; 
List<int[]> fooList = Arrays.asList(fooArray); 
//fooList contains a single element which is fooArray 

所以,你應該使用的包裝類的:

Integer[] fooArray = { 1, 2, 3 }; 
List<Integer> fooList = Arrays.asList(fooArray); 
//fooList contains 3 elements: 1, 2, 3 

IMO你不應該在一個Map使用集合作爲重點,除非它是一個具體的要求。相反,我會嘗試搜索其他選項。

相關問題