如何让这个 HashMap<Integer[], Integer> 以我想要的方式工作?

How do I get this HashMap<Integer[], Integer> to work the way I want it to?

在我的程序中,我想使用 Integer[]s 的 HashMap,但是我在检索数据时遇到了问题。经过进一步调查,我发现这个程序中没有任何其他内容,打印 null.

HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
Integer[] b = {5, 7};
Integer[] c = {5, 7};
a.put(b, 2);
System.out.println(why.get(c));

如果不需要,我不想用 a.keySet() 遍历 HashMap。还有其他方法可以达到预期效果吗?

数组基于从对象本身计算的散列存储在映射中,而不是基于其中包含的值(使用 == 和对数组使用 equals 方法时会发生相同的行为)。

您的密钥应该是正确实现 .equals 和 .hashCode 的集合,而不是普通数组。

检查此代码的 un/desired 行为:

// this is apparently not desired behaviour
{
    System.out.println("NOT DESIRED BEHAVIOUR");
    HashMap<Integer[], Integer> a = new HashMap<Integer[], Integer>();
    Integer[] b = { 5, 7 };
    Integer[] c = { 5, 7 };
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}
// this is the desired behaviour
{
    System.out.println("DESIRED BEHAVIOUR");
    HashMap<List<Integer>, Integer> a = new HashMap<List<Integer>, Integer>();
    int arr1[] = { 5, 7 };
    List<Integer> b = new ArrayList<Integer>();
    for (int x : arr1)
        b.add(x);

    int arr2[] = { 5, 7 };
    List<Integer> c = new ArrayList<Integer>();
    for (int x : arr2)
        c.add(x);

    System.out.println("b: " + b);
    System.out.println("c: " + c);
    a.put(b, 2);
    System.out.println(a.get(c));
    System.out.println();
}

输出:

NOT DESIRED BEHAVIOUR
null

DESIRED BEHAVIOUR
b: [5, 7]
c: [5, 7]
2

您可能还想检查这两个问题:

  • Java Array HashCode implementation
  • How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java