简体   繁体   中英

using hashCode to return huge Integer ids for 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?

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; 

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