简体   繁体   中英

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

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

You can use a List<Integer> as key instead of 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM