Most common interview questions are “How HashMap works in java”, “How get and put method of HashMap work internally”. Here I am trying to explain internal functionality with an easy example. Rather than going through theory, we will start with example first, so that you will get better understanding and then we will see how get and put function work in java. Lets take a very simple example. I have a Country class, we are going to use Country class object as key and its capital name(string) as value. Below example will help you to understand, how these key value pair will be stored in hashmap.
1. Country.java
01
packageorg.arpit.javapostsforlearning;
02
publicclassCountry {
03
04
String name;
05
longpopulation;
06
07
publicCountry(String name, longpopulation) {
08
super();
09
this.name = name;
10
this.population = population;
11
}
12
publicString getName() {
13
returnname;
14
}
15
publicvoidsetName(String name) {
16
this.name = name;
17
}
18
publiclonggetPopulation() {
19
returnpopulation;
20
}
21
publicvoidsetPopulation(longpopulation) {
22
this.population = population;
23
}
24
25
// If length of name in country object is even then return 31(any random number) and if odd then return 95(any random number).
26
// This is not a good practice to generate hashcode as below method but I am doing so to give better and easy understanding of hashmap.
Now put debug point at line 23 and right click on project->debug as-> java application. Program will stop execution at line 23 then right click on countryCapitalMap then select watch.You will be able to see structure as below.
Now From above diagram, you can observe following points
There is an Entry[] array called table which has size 16.
This table stores Entry class’s object. HashMap class has a inner class called Entry.This Entry have key value as instance variable. Lets see structure of entry class Entry Structure.
1
staticclassEntry implementsMap.Entry
2
{
3
finalK key;
4
V value;
5
Entry next;
6
finalinthash;
7
...//More code goes here
8
}
Whenever we try to put any key value pair in hashmap, Entry class object is instantiated for key value and that object will be stored in above mentioned Entry[](table). Now you must be wondering, where will above created Enrty object get stored(exact position in table). The answer is, hash code is calculated for a key by calling Hascode() method. This hashcode is used to calculate index for above Entry[] table.
Now, If you see at array index 10 in above diagram, It has an Entry object named HashMap$Entry.
We have put 4 key-values in hashmap but it seems to have only 2!!!!This is because if two objects have same hashcode, they will be stored at same index. Now question arises how? It stores objects in a form of LinkedList(logically).
So how hashcode of above country key-value pairs are calculated.
1
Hashcode forJapan = 95as its length is odd.
2
Hashcode forIndia =95as its length is odd
3
HashCode forRussia=31as its length is even.
4
HashCode forFrance=31as its length is even.
Below diagram will explain LinkedList concept clearly.
So now if you have good understanding of hashmap structure,Lets go through put and get method.
Put :
Lets see implementation of put method:
01
/**
02
* Associates the specified value with the specified key in this map. If the
03
* map previously contained a mapping for the key, the old value is
04
* replaced.
05
*
06
* @param key
07
* key with which the specified value is to be associated
08
* @param value
09
* value to be associated with the specified key
10
* @return the previous value associated with <tt>key</tt>, or <tt>null</tt>
11
* if there was no mapping for <tt>key</tt>. (A <tt>null</tt> return
12
* can also indicate that the map previously associated
13
* <tt>null</tt> with <tt>key</tt>.)
14
*/
15
publicV put(K key, V value) {
16
if(key == null)
17
returnputForNullKey(value);
18
inthash = hash(key.hashCode());
19
inti = indexFor(hash, table.length);
20
for(Entry<k , V> e = table[i]; e != null; e = e.next) {
Key object is checked for null. If key is null then it will be stored at table[0] because hashcode for null is always 0.
Key object’s hashcode() method is called and hash code is calculated. This hashcode is used to find index of array for storing Entry object. It may happen sometimes that, this hashcode function is poorly written so JDK designer has put another function called hash() which takes above calculated hash value as argument.If you want to learn more about hash() function, you can refer hash and indexFor method in hashmap.
indexFor(hash,table.length) is used to calculate exact index in table array for storing the Entry object.
As we have seen in our example, if two key objects have same hashcode(which is known as collision) then it will be stored in form of linkedlist.So here, we will iterate through our linkedlist.
If there is no element present at that index which we have just calculated then it will directly put our Entry object at that index.
If There is element present at that index then it will iterate until it gets Entry->next as null.Then current Entry object become next node in that linkedlist
What if we are putting same key again, logically it should replace old value. Yes,it will do that.While iterating it will check key equality by calling equals() method(key.equals(k)), if this method returns true then it replaces value object with current Entry’s value object.
Get:
Lets see implementation of get now:
01
/**
02
* Returns the value to which the specified key is mapped, or {@code null}
03
* if this map contains no mapping for the key.
04
*
05
* <p>
06
* More formally, if this map contains a mapping from a key {@code k} to a
07
* value {@code v} such that {@code (key==null ? k==null :
08
* key.equals(k))}, then this method returns {@code v}; otherwise it returns
09
* {@code null}. (There can be at most one such mapping.)
10
*
11
* </p><p>
12
* A return value of {@code null} does not <i>necessarily</i> indicate that
13
* the map contains no mapping for the key; it's also possible that the map
14
* explicitly maps the key to {@code null}. The {@link #containsKey
15
* containsKey} operation may be used to distinguish these two cases.
16
*
17
* @see #put(Object, Object)
18
*/
19
publicV get(Object key) {
20
if(key == null)
21
returngetForNullKey();
22
inthash = hash(key.hashCode());
23
for(Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
As you got the understanding on put functionality of hashmap. So to understand get functionality is quite simple. If you pass any key to get value object from hashmap.
Key object is checked for null. If key is null then value of Object resides at table[0] will be returned.
Key object’s hashcode() method is called and hash code is calculated.
indexFor(hash,table.length) is used to calculate exact index in table array using generated hashcode for getting the Entry object.
After getting index in table array, it will iterate through linkedlist and check for key equality by calling equals() method and if it returns true then it returns the value of Entry object else returns null.
Key points to Remeber:
HashMap has a inner class called Entry which stores key-value pairs.
Above Entry object is stored in Entry[ ](Array) called table
An index of table is logically known as bucket and it stores first element of linkedlist
Key object’s hashcode() is used to find bucket of that Entry object.
If two key object ‘s have same hashcode , they will go in same bucket of table array.
Key object ‘s equals() method is used to ensure uniqueness of key object.
Value object ‘s equals() and hashcode() method is not used at all
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步