如何使阵列为重点的HashMap的工作? [英] How to make HashMap work with Arrays as key?

查看:96
本文介绍了如何使阵列为重点的HashMap的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用布尔数组作为一个HashMap的键。但问题是HashMap中失败时不同的数组作为密钥传递到拿到钥匙,虽然元件是一样的。 (因为它们是不同的对象)。

I am using boolean arrays as keys for a HashMap. But the problem is HashMap fails to get the keys when a different array is passed as key, although the elements are same. (As they are different objects).

我怎样才能使其与数组作为键的作用?
这里是code:

How can I make it work with arrays as keys ? Here is the code :

public class main {
public static HashMap<boolean[], Integer> h;


public static void main(String[] args){
    boolean[] a = {false, false};

    h = new HashMap<boolean[], Integer>();
    h.put(a, 1);


    if(h.containsKey(a)) System.out.println("Found a");

    boolean[] t = {false, false};

    if(h.containsKey(t)) System.out.println("Found t");
    else System.out.println("Couldn't find t");

}

}

这两个数组 A T 包含相同的元素,但是HashMap不能对<返回任何code> T 。

Both the arrays a and t contain the same elements, but HashMap doesn't return anything for t.

我如何工作的?

推荐答案

您不能做这种方式。无论 T A 将有不同的散code()值,因为在 java.lang.Array.hash code()方法是从 Object继承,它使用参考计算散列code(缺省实现)。因此,哈希code数组是参考相关的,这意味着你会得到不同的散列code为 T 值和。此外,等于,因为这也是基于参考两个阵列将无法工作。

You cannot do it this way. Both t and a will have different hashCode() values because the the java.lang.Array.hashCode() method is inherited from Object, which uses the reference to compute the hash-code (default implementation). Hence the hash code for arrays is reference-dependent, which means that you will get a different hash-code value for t and a. Furthermore, equals will not work for the two arrays because that is also based on the reference.

您可以做到这一点的唯一方法是创建一个保持布尔阵列作为一个内部成员的自定义类。然后,你需要重写等于散code 在确保这样的方式包含数组与实例相同的值相等,也有相同的散列code。

The only way you can do this is to create a custom class that keeps the boolean array as an internal member. Then you need to override equals and hashCode in such a way that ensures that instances that contain arrays with identical values are equal and also have the same hash-code.

这是更容易的选择可能是使用列表&LT;布尔&GT; 的关键。按照文档的为列表 散code()实现定义为:

An easier option might be to use List<Boolean> as the key. Per the documentation the hashCode() implementation for List is defined as:

int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
    E obj = i.next();
    hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}

正如你所看到的,它取决于你的列表里面的参考,而不是值,所以这应该为你工作。

As you can see, it depends on the values inside your list and not the reference, and so this should work for you.

这篇关于如何使阵列为重点的HashMap的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆