4

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?

Toseef Zafar
  • 1,601
  • 4
  • 28
  • 46

1 Answers1

3

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; 
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
  • Sorry, that 'could be' indicates pure speculation here. Hash tables dont work that way. – Gyro Gearless Feb 11 '19 at 15:58
  • 1
    Actually, that is a simplified but otherwise accurate description of exactly how `HashMap` works, per the official docs and source, @Gyro Gearless. No speculation needed. – Lew Bloch Feb 11 '19 at 20:37