如何使 HashMap 以数组为键工作? [英] How to make HashMap work with Arrays as key?
问题描述
我使用布尔数组作为 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).
如何让它以数组为键?这是代码:
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 不为t
返回任何内容.
Both the arrays a
and t
contain the same elements, but HashMap doesn't return anything for t
.
我如何使它工作?
推荐答案
你不能这样做.t
和 a
都会有不同的 hashCode()
值,因为 java.lang.Array.hashCode()
> 方法继承自 Object
,它使用引用来计算哈希码(默认实现).因此,数组的哈希码是依赖于引用的,这意味着您将获得 t
和 a
的不同哈希码值.此外,equals
不适用于这两个数组,因为这也是基于引用的.
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.
您可以这样做的唯一方法是创建一个自定义类,将 boolean
数组保留为内部成员.然后,您需要覆盖 equals
和 hashCode
,以确保包含具有相同值的数组的实例相等并且也具有相同的哈希码.
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.
更简单的选择可能是使用 List
作为键.根据文档,<List
的 code>hashCode() 实现定义为:
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屋!