Saturday, July 27, 2013

Java : How HashMap stores and returns element

Hashing technique is useful in searching exact data in very short time.
In Java Collection Framework, Hashmap class provides functionality to store data using hashing techniques.
Here is how HashMap works internally.

Following main parameters are used to store data in HashMap:
  • Internal static class Entry which contains following variables
    • Key
    • Value
    • Next element
    • Hash value
  • Array of Entry objects (Bucket)
  • Threshold (Initial capacity * load factor)


While putting element in HashMap:
·         If key is null, it allows putting single value against null key. If you are trying to add another value against null key, it returns existing value in HashMap against null key and stores new value against null key.
o   Entry Object is stored at Bucket location 0. Hash value is also zero for null key.


·         How Value is stored against key in HashMap:
  •       Internal hash function is used to calculate hash value for hashcode of key. Hashcode of key is passed to hash function to get hash value.
  • Bucket index is found based on hash value and length of bucket. (Bucket is array which is used to store data. Data is Entry objects which contains key, value, next object and hash values). Bucket index = hash value & (bucket size-1). Bitwise and operator is used to find out index value.
  • Iterator is used to iterate over Entry objects at given index (if exists) to check if same key is already exists by comparing hash value and object equality using equals function. If same key is found, new value is stored against key and old value is returned.

No comments: