user2399453
user2399453

Reputation: 3081

Hashing an array to an integer

I have a mapping from an int[2] array to weights. So [2, 3] -> 5, [4,5] -> 6 etc. Is it a workable strategy to use a HashMap where I do h.put(Arrays.deepHashCode(a), w)? I have a large amount of data and I want to be able to quickly look up weights given coordinates x,y. I am seeing bugs where h.get(hashcode) seems to be returning me unexpected values later. Not always but occasionally. Is this possibly an artifact of the fact that [x,y] and [a, b] might occasionally have the same deepHashCode()? I will try to boil it down to a small piece of code but currently its hard to isolate this problem.

EDIT: I isolated the problem. Turns out Arrays.deepHashCode([2, 74]) is same as Arrays.deepHashCode([3, 43]) [both return 1097 on my system]. I incorrectly thought that the get() would resolve collisions for me.. but it can't since its mapping a hashcode to a value and the array key is no longer in existence when I did the put().

Upvotes: 0

Views: 71

Answers (2)

Alan
Alan

Reputation: 478

Using arrays as keys in a map is a bad idea, as their hashCode implementation is not based on their contents. You should instead use a collection in place of your array(s), or a class that wraps your array and properly implements equals and hashCode.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198014

You should never assume that hash codes are unique. Always remember that return 0 is a valid implementation of hashCode().

You should really be writing a pair or a tuple class instead of using arrays or manually putting in hash codes that you should not assume are unique.

Upvotes: 2

Related Questions