[英]Why Does My Hashmap Not Register (Work)
抱歉,標題不夠詳盡,因為我還很新。
只是發生了什么事,我想注冊一個食譜(請參見下面的代碼)。 然后,我要檢查輸入配方是否與注冊配方匹配。 我正在通過哈希映射和數組。
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,arrays方法是否做錯了,如果可以,我如何獲得想要的結果?
不要將數組( Object[]
或int[]
或其他數組)用作Map
鍵,因為數組不會覆蓋hashCode
或equals
方法。
如果必須使用數組作為鍵,請改用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
的鍵。 相反,我將嘗試搜索其他選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.