Search code examples
javahashmap

Java Hashmap containsKey returns false for existing key


There is this problem in my code I'm trying to figure out the source of the problem, It seems quite deep and I can't figure it out. I have some really major clues, yet I feel something is missing in my understanding so I can't figure out how to fix it.

In my code, i'm calling a constructor from a different class of an object with a field of a Hashmap<Integer[], Integer[]> and when I debug I see that the map does contain the key I'm looking for. Here map contains one mapping which maps the array {0} to the array {0}:

Integer[] key = {0};
boolean contains = obj.map.containsKey(key); // is false in the debugger

Though If I initialize a new Hashmap it behaves differently:

Hashmap<Integer[], Integer[]> map = new Hashmap();
Integer[] key = {0};
Integer[] val = {0};
map.put(key,val);
boolean contains = map.containsKey(key); // is true in the debugger

I see one clear difference between the cases, that in the second case, the variable "key" and the actual key in the Hashmap are the same object, though in the first they are somehow not the same object. I guess this is what causes the difference. But I can't seem to get how can I control the key always being the same object in the map, or how should I implement this such that keys will always be found. I would use int instead of Integer but this is not allowed in Hashmap so how should be the correct workflow in such a case?

P.S I hope the code is clear enough because it is a hell lot of code to add here to get the entire thing running. If it is necessary I will try to compose a new, more clear, and short code to demonstrate the problem, though I am hoping it can be explained without it.

Thanks


Solution

  • Arrays are not suitable keys for HashMaps, since arrays don't override equals() and hashCode() of Object class.

    As a result, two arrays that have the exact same elements are not considered equal to each other by HashMap.

    You can use List<Integer> instead of Integer[] as the key of your HashMap, since Lists do override equals() and hashCode() (and so does Integer).