How does the HashMap internally works?

Hashmap is used mainly to store key-value pairs.
The purpose of a map is to store items based on a key that can be used to retrieve/delete the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.
When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in.
Basically hashmap is composed of hashmap bucket (1 hashtable ), each of the buckets pointing to its own Linked List of entries nodes. So when one tries to insert a new key-value Object pair into a hashmap (using put() method in java) the key-Object’s own function hashcode() is used to calculate the correct bucket to insert such pair.
Let’s go in details now >>
Q: What is a Hash Function ?
Q: What is hashmap's Bucket ?
Q: How does HashMap get(Key k) method works ?
- checks whether key is null or not (only 1 null key possible)
- calls hashCode method on the key object
- applies returned hashValue to its own static hash function (It defends against poor quality hash functions.) to find a bucket location(backing array)
- if in a single bucket 2 entries has same hash Value - then uses key.equals()
Q: How will you measure the performance of HashMap ?
An instance of HashMap has two parameters that affect its performance: initial capacity (buckets) and load factor. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
Q: Pros/Cons of Hashmap , in difference between HashTable vs HashMap ?
Hashtable is synchronized, whereas HashMap is not.
 Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
One of HashMaps subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

0 comments:

Post a Comment

My Instagram