How Hashmap Works Internally in Java
Tags: Core Java, Hashmap, Internal Working, Maps

In this post, we will discuss the internal working of hashmap. Being the famous question in the interview lets discuss the internal working of hashmap.Before discussing how the hashmap works let discuss some of the important terminologies which will be used further in the blog.

Hashmap is a java class which stores the object in the form of key, value pair. Each key is associated with a value. We can understand this as each person can be identified using the unique mobile number. Here, in this example, the phone number is the key and person object is the value. So, in java we can define the hashmap in the following way :

Map<String,value> map = new HashMap<String,value>();

Terminologies related to hashmap –

1. Hashing Principle –

The hashmap works on the principle of hashing. Hashing is nothing but transforming the given entity to some number. So basically hashing depends upon the function which returns the integer value. This integer number is known as hashcode.

2. Bucket –

Bucket in hashmap is nothing but the entry of multiple singly linked list. These LinkedList are registered as an array of Entry.

3. Collision –

The collision occurs when we try to add different keys with the same hash. So, in simple terms collision in hashmap will occur when hashmap finds two objects have the same hashcode.

4. Load Factor –

It is the measuring unit which decides on exactly when the hashmap needs to be resized. Resizing hashmap means increasing the size of the bucket. The default capacity of hashmap is 16 and to that of default load factor is 0.75.

5. Threshold –

The threshold is the next size value of the hashmap to which it needs to be resized. Resize will happen once the hashmap is full. The threshold value will be calculated based on the below formula:

Threshold = CurrentCapacity * LoadFactor

For example :

If the hashmap is created with the initial capacity of 16 and a load factor of 0.75, then, the threshold will be 16 * 0.75 = 12.

So, these were some of the important terminologies which relate to the hashmap. Now, one more important thing or rule that we should discuss while discussing hashmap. The rule is The contract between hashcode and equals method. The contract states that:

1. If two objects are equal based on the equals method then their hashcode will be equal.

2. If two objects have the same hashcode then they may or may not be equal.

Now, after becoming familiar to these terminologies we are good to go with the interview questions. Let’s discuss them.

Q1. What is a hashmap in java?

Hashmap is a java class which stores the object in the form of key, value pair. Each key is associated with a value. We can understand this as each person can be identified using the unique mobile number. Here, in this example, the phone number is the key and person object is the value. So, in java we can define the hashmap in the following way :

Map<String,value> map = new HashMap<String,value>();

Q2. How hashmap works internally in java / Explain the internal working of get() in hashmap?

Internally hashmap works on the principle of hashing. Hashmap provides put(key, value) for adding the values in the hashmap and get(key) to get the object which corresponds to the specified key.

While inserting the object into the hashmap we call put(key, value), hashmap internally calls the hashcode method on the key object to apply the hashing mechanism. This hashcode returns the integer value which is known as hashcode. This hashcode is then can be used to find the bucket location for storing an Entry object. Hashmap will store both key and value pair in the form of Map.Entry.

Q3.What will happen if the two objects have the same hashcode?

This is the case of collision. In this case, before answering we should remember the contract between hashcode and equals method. Since hashcode is the same bucket value will also be same and collision will occur. Hashmap internally uses LinkedList to store objects. Hence, this entry will be stored in LinkedList.

Q4. How we can retrieve the object if two keys have the same hashcode?

Hashmap handles this case by using the mechanism called Channing. Hashmap uses LinkedList to deal with collision and store the objects into the bucket. It will be better understood by the below:

Q5. What is the difference between hashmap and hashtable?

The main difference between hashmap and hashtable are as follows:

Hashmap is non-synchronized. It is not thread-safe hence, we should not use it in case of multi-threaded environment whereas Hashtable is synchronized. Means it is thread-safe and hence we can use hashtable in a multi-threaded environment. As hashmap is non-synchronized the performance is much faster whereas Hashtable is synchronized which makes it slower as compare to the hashmap. Hashmap allows one null key and multiple null values whereas Hashtable does not allow any number of null key and null values. To make hashmap synchronized we can use this code Map m = Collections.synchronizedMap(hashmap) whereas Internally hashmap is already synchronized Hashmap can be traversed using iterator whereas Enumerator an Iterator can be used to traverse the hashtable. Iterator in hashmap is fail-fast whereas Enumerator in hashtable is not fail-fast.

Q6. Why string is used as a key in hashmap?

Since the string is an immutable class in java, its hashcode can be calculated at the time creation and it does not need to be recalculated. Hence, its processing is faster than other hashmap key objects. All the wrapper classes in java are eligible for hashmap key.

Q7. Can we create a custom key in hashmap? If yes, how?

Yes, we can create the custom key in hashmap. To do so there are some of the rules that we need to follow:

1). The class which we will be using as the hashcode key, that class should be immutable.

2). The class should implement equals and hashcode methods. Hashcode will be used when we insert a key object into the map and equals method will be used when we retrieve the object.

Below is the example of a sample class which is eligible for hashmap key:

<script src=”https://gist.github.com/sourabhrai235/e470a94df5b36a3853b50a28eec1efa6.js"></script>

Q8. Can we store the null key in hashmap?

Yes, we can store the null key in hashmap. Only one null key is allowed in the hashmap. This entry will be stored as the first location on the bucket array. The Hashmap does not call hashcode() on the null key as it will throw NullPointerException. Hence, when the user calls get() with null, then the value of the first index is returned.

Q9. Can we store null values in hashmap?

Yes, hashmap also allows null value. We can store any number of null values in the hashmap.

Q10. Which data structure is used to implement hashmap?

HashTable is the based implementation of HashMap. HashMap also uses Array and LinkedList. The array data structure is used as the bucket while LinkedList is used to store all mapping which lands in the same bucket. Java 8 onwards, LinkedList is replaced by binary search tree.

Q11. What will happen if we use hashmap in a multithreaded application?

If you use HashMap in a multidimensional environment in such a way that multiple threads structurally modify the mapping by adding, removing, or modifying the map, then HashMap’s internal data structure may be corrupted as if some links are missing. , Some may indicate incorrect entries, and the map itself may be completely useless. Because of these drawbacks, we should not use HashMap in such environment hence, we can use ConcurrentHashMap or HashTable which ensures thread-safety.

Q12. What is ConcurrentHashmap?

ConcurrentHashMap is synchronized. As HashMap does not provide thread-safety so, ConcurrentHashMap can be used in the threaded environment. ConcurrentHashMap is fail-safe and it returns ConcurrentModificationException during iteration. ConcurrentHashMap does not allow null key/value. It will throw NullPointerException. ConcurrentHashMap is slower than HashMap.

Q13. What are the different ways to iterate over hashmap?

Here are the ways using which we can iterate the HashMap, By using

keyset and iterator

entrySet and iterator

entrySet and enhanced for loop

keyset() and get()

That’s about some of the important questions from the Java HashMap interview. I’ve also tried to answer them, but if you disagree with an answer, feel free to comment. HashMap is a very important class in java, so I suggest everyone go through HashMap and its features in-depth.

Related Articles:

1. Core java interview questions.

2. Java 8 interview questions.

3. Abstraction in Java.

4. Encapsulation in Java.

5. Compile time polymorphism in java.

6. Runtime Polymorphism in java.