Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using hashCode to return huge Integer ids for HashMap

Tags:

java

hashmap

HashMap works with fixed length arrays internally and indexes where values will are stored are based on hash of the key, and in case of collion for hash it will make a linked list on that index and then will use equals method to return the correct value while reading.

I have a custom class which has got an Integer id as a sequential number, I used this class as 'key' of the HashSet and in hasCode() method I am return the id, which means that the underlying array of HashSet will look for index number N that I return from hasCode() to store the value.

Now, even if I return Integer.MAX_VALUE - 1 from the hashCode() the HashMap is able to store the value in the map. The question is, is Integer.MAX_VALUE -1 being used as index of underlying array? If yes, does the HashMap create that huge array when we create its instance?

like image 828
Toseef Zafar Avatar asked Sep 08 '25 11:09

Toseef Zafar


1 Answers

No, this is not the case. Hashmap would allocate an array of 16 elements initially and then resize depending on the loading factor. So in the case of hash code returning an integer that won't fit in that array or even a negative number, there is a simple mechanism that could be used like absolute value of the mod. In a simplified form:

 int arrayIndex = abs(hashCode) % arraySize; 
like image 165
Sleiman Jneidi Avatar answered Sep 11 '25 07:09

Sleiman Jneidi