(957 Views)

HashMap is one of the most widely used data structures in Java Collection. Insertion and Retrieval are the most frequently used operations, and HashMap execute these processes in constant time, no matter how big the data is. It stores key-value pairs and to access a value, one must know it's key.

- It is present in java.util package.
- Keys are stored with Hashing technique.
- Duplicate Keys are not allowed, but more than one key can contain the same object.
- Ordered arrangement of Keys is not guaranteed.

- Initial Capacity
- Load Factor

HashMap is built on the principle of HashTable. The capacity in Hash Table points to the bins it has. Using some Hashing Algorithm, all the keys are stored in these bins. If there are multiple keys at the same bin, chaining in the form of linked list is used.

Here's an example of a Hash Table.In our example, the capacity is 7.

When we instanciate a HashMap, it has initial capacity of 16; which means there are 16 bins initially in it.

Consider a scenario when you have just 16 bins and you have to add 160 items to it. Even if all the items are distributed equally, every bin will have a chain of length 10. In this case, lookup cost will be very high which violates the very purpose of a HashMap. So we need to increase the number of bins OR the capacity of the HashMap.

The decision regarding when to increase the capacity of the HashMap is taken on the basis of Load Factor. It sets a threshold beyond which, capacity is doubled. Load Factor's value lies between 0 and 1 and the default value is 0.75.

Lets assume out Load factor is 0.50 and capacity is 16,

Threshold = Load Factor * Capacity,

Threshold = 0.50 * 16 = 8

If we set Load Factor to be a high value, Space used by the HashMap will be very low. On the other hand, it is almost filled at every time, which makes lookup cost (time) very high.

If we set Load Factor to be a low value, Space used by the HashMap will be very high. On the other hand, it is mostly empty at every time, which makes lookup cost (time) very low.

0 UpvotesUpvote |
0 DownvotesDownvote |

- Difference between merge and update methods in hibernate [1170 Views]
- Java Program to Swap two Numbers without using third variable [1615 Views]
- Lee Algorithm in Java [1728 Views]
- Difference between StringBuilder insert and append method [901 Views]
- Simple Tutorial on working with Java Spring and AngularJS together [707 Views]

- Algorithm to find whether number is Armstrong Number or Not [40208 Views]
- How To Win Ludo King Game Every Time [39334 Views]
- Jio Phone hang on LOGO problem Solution - Hard Reset Jio Phone [27644 Views]
- Knuth-Morris-Pratt (KMP) Substring Search Algorithm with Java Example [27544 Views]
- FlowChart and Algorithm to find Whether a Number is Even or Odd [20020 Views]