很抱歉,如果标题不能解释这个,因为我还不是新人。
简单地说,我想要注册食谱(参见下面的代码)。然后我想检查输入配方是否与注册配方匹配。我是通过哈希映射和数组来做到这一点的。
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 :(得分:2)
不要使用数组(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
中的密钥。相反,我会尝试搜索其他选项。