How a HashMap internally works


How does it work?

  • The initial capacity of a HashMap is 16.
  • When you create a HashMap it will create a map with 16 buckets (0 to 15).
  • Each bucket is a LinkedList.
  • As we know a LinkedList contains nodes and each node contains a key, value, hash value, and a pointer to the next node.
  • When we add data into the HashMap, in the put() method, internally it will generate an index using the key.
  • That index should be 1 to 15.
  • For example, if it gets an index = 5, it will store that data in the 5th bucket.
  • Please check the below example.

Employee emp1 = new Employee(1,'Ann')
Employee emp2 = new Employee(2,'John')
Employee emp3 = new Employee(3,'Rex')

Map<Employee, String> hashMap = new HashMap<>();

hashMap.put(emp1, 'IT');
hashMap.put(emp2, 'DEV');
hashMap.put(emp3, 'QA');
hashMap.put(null, 'QA');

  • In this example, I have created an Employee and three employee objects.
  • I am going to use employees as a key in the hash map.
  • In the first case, I am going to add emp1 as the key in the hash map.
  • Inside the put method, it will generate an index and, according to the index the value will be stored in the bucket.
  • For example for another value, if it generates the same index, a hash collision can happen.
  • In this case, it is required to have equals() and hashcode() methods inside the Employee object.
  • It will check the equality of the objects using the equal() method and then if it is not equal it will be saved in the same bucket as the next node to the existing node.
  • If you put null values as the key, it will be saved in the 0th bucket. 

How a HashMap internally works How a HashMap internally works Reviewed by Ravi Yasas on 6:54 PM Rating: 5

No comments:

Powered by Blogger.