Reputation: 1767
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?
Upvotes: 4
Views: 155
Reputation: 23329
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;
Upvotes: 3