[英]Is there a way to use the containsKey() map function on an Object key?
I have a hashmap with entries containing an integer array as a key and an integer as a value.我有一个哈希图,其中包含一个整数数组作为键和一个整数作为值。 When I add entires to the hashmap I create integer array variables and then use the variable name in the hashmap.put() call.
当我向 hashmap 添加整数时,我创建整数数组变量,然后在 hashmap.put() 调用中使用变量名称。 The problem is that I later need to search the hashmap keys to see if a given integer array key exists, but the hashmap.containsKey() call always returns false because the hashmap contains a reference to the integer array and not an actual explicit integer array.
问题是我稍后需要搜索 hashmap 键以查看给定的整数数组键是否存在,但是 hashmap.containsKey() 调用始终返回 false,因为 hashmap 包含对整数数组的引用而不是实际的显式整数数组.
Is there an easy way I can search the hashmap using a given integer array?有没有一种简单的方法可以使用给定的整数数组搜索哈希图?
Here is the code fragment:这是代码片段:
public static void main (String[] args) {
Map<int[], Integer> map = new HashMap<int[], Integer>();
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {5, 6, 7, 8};
map.put(arr1, 1);
map.put(arr2, 2);
int[] arr3 = {1, 2, 3, 4};
System.out.println(map.containsKey(arr3));
}
An array is not suitable as a key of a HashMap
, since arrays don't override the default implementation of equals
and hashCode
.数组不适合作为
HashMap
的键,因为数组不会覆盖equals
和hashCode
的默认实现。 Therefore, two different array objects (such as your arr1
and arr3
) are not equal even if they contain the exact same elements and in the same order.因此,即使两个不同的数组对象(例如您的
arr1
和arr3
)包含完全相同的元素且顺序相同,它们也不相等。
You can use a List<Integer>
as key instead of int[]
.您可以使用
List<Integer>
作为键而不是int[]
。 That will work.那可行。
First, you cannot use primitive values in generics.
首先,您不能在泛型中使用原始值。
Your code will not compile.
您的代码将无法编译。
Second, you should never use mutable values as hash table keys.其次,永远不要使用可变值作为哈希表键。
Formally, you can use List<Integer>
instead of int[]
, but this will lead to hard-to-debug bugs in the future.正式地,您可以使用
List<Integer>
而不是int[]
,但这将导致将来难以调试的错误。 When you access or search by key in a hash table, a hash code is calculated for your value and searched for a constant time in the list of known for this hash table.当您在哈希表中按关键字访问或搜索时,将为您的值计算一个哈希码,并在此哈希表的已知列表中搜索恒定时间。 If your code changes the object that you defined with the key, then you will no longer find that key-value pair in the hash table.
如果您的代码更改了您使用键定义的对象,那么您将不再在哈希表中找到该键值对。
I do not recommend that you use List<Integer>
as the hash table key, although this will solve the problem described in the question.我不建议您使用
List<Integer>
作为哈希表键,尽管这将解决问题中描述的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.