Tuesday, May 26, 2020

How does HashMap works in Java

  • Array created with default capacity of 16
  • Then getting hash code of the key
  • It rehashes the hash code to prevent against a bad hashing function from the key that would put all data in the same index (bucket) of the inner array
  • It takes the rehashed hash hashcode and bit-masks it with the length (minus 1) of the array. This operation assures that the index can’t be greater than the size of the array. You can see it as a very computationally optimized modulo function.

  • Finding appreciate array index according to hash code and saving in bucket associated with this index
  • In Java 8 , if bucket size more than 8 automatically converting that bucket from linked list to read black tree
  • Can auto size the map according to load factor. Initial arrays size is 16 and load factor is 0.75
  • HashMap is not thread safe but HashTable is thread safe but locks whole data structure during concurrent access.  On the other hand , ConcurrentHashMap is locking only bucket
  • Mostly Integer and String used as map key because they immutable and provide string hash code function
  • If you have too many data to put on Map , it is advisable to create map with approximate high initial capacity. Because there is additional overhead of shrinking the map


Youtube : link




No comments:

Post a Comment

Thank you for your comment!