【问题标题】:How do I get this HashMap<Integer[], Integer> to work the way I want it to?如何让这个 HashMap<Integer[], Integer> 以我想要的方式工作?
【发布时间】:2015-07-02 19:40:27
【问题描述】:

在我的程序中,我想使用 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。有没有其他方法可以达到预期的效果?

【问题讨论】:

  • 您还没有指定您期望从这段代码中获得什么行为?而且why 也没有在任何地方定义。

标签: java hashmap


【解决方案1】:

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

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

【讨论】:

  • 最好是不可修改的集合,例如与Collections.unmodifiableCollection.
【解决方案2】:

检查此代码是否有不希望的行为:

// 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多