5 interview questions and answers on HashMap in Java
5 interview questions and answers on HashMap in Java. HashMap is one of the widely used type of Collection in Java. So it is very important to know some of the key things in HashMap such as How HashMap works, HashMap get() and put() methods, HashMap size etc. Lets see some of the interview questions with answers on HashMap.
Have you used HashMap and why it is used?
This is a very common question and asked frequently, this question is only for understanding that you have used HashMap or not. But as we often use HashMap, we can say that HashMap is a Collection which works on principle of Hashing and it uses key and value pairs to store the information and we can get the value if we pass key to the HashMap. You can also say HashMap is fast as it is not synchronized, HashMap accept null etc,
How HashMap works in java?
This is another frequently asked interview question in java, You can get more detailed answer here.
How get() method works if two different objects have same hashcode?
As we seen in second question’s answer two unequal object in Java can have same hashcode, so here question arises if keys we are using for retrieving the value has same hashcode, then it will be problem for retrieving, but fortunately its not because HashMap stores both Key and Value in LinkedList node or as Map.Entry. So when we find the address of a bucket using the hashcode then HashMap calls keys.equals() method for identifying for which key we want the value in a LinkedList and return associated value object for that key in Java HashMap.
Why Immutable classes such as String are considered good keys for HashMap?
We all know String is immutable and final if you don’t know please check why String is immutable in java? Immutabilty is very essential in order to prevent changes on fields which are used to calculate hashcode. And hashcode is the address to find the bucket location. So key object correctly overrides equals and hashcode methods and follow the contract strictly, then there is less chances of collision which results in efficiency of HashMap.
What is the load factor in java HashMap and what happens when size of the HashMap exceeds a given threshold defined by load factor?
Load factor of HashMap is is .75 it will act to re-size the map once it filled 75%, so once size exceeds 75%, then Java HashMap re-size itself by creating a new bucket array of size twice of size defined previously for the HashMap ,then it start putting every old element into that new bucket array. This process is also called rehashing because hash function is used to find the new bucket location.
If you know more questions about HashMap in Java then you can write in comment section.