SlideShare a Scribd company logo
1 of 20
Hashmap Internal Working
in Java
Introduction
HashMap is a part of Java’s collection since Java 1.2. It provides the basic
implementation of Map interface of Java. It stores the data in (Key, Value) pairs.
Equals and hashcode methods
In order to understand the internal working of HashMap, we must be aware of hashcode and equals method.
equals(Object otherObject) – As method name suggests, it is
used to simply verify the equality of two objects.
hashcode() – is a integer code generated for any variable/object
after applying a formula/algorithm on its properties. The hash code
for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], where
s[i] is the ith character of the string, n is the length of the string.
What’s the output?
public static void main(String[] args) {
String s1 = "Compassites";
String s2 = "Software";
System.out.println( s1.equals(s2) );
System.out.println("Compassites " + s1.hashCode() );
System.out.println("Ea " + s2.hashCode() );
}
It Produces the following output.
false
Compassites hashCode: 1297712907
Software hasCode: 1383974343
What about this?
public static void main(String[] args) {
String s1 = "FB";
String s2 = "Ea";
System.out.println( s1.equals(s2) );
System.out.println("FB hashcode " + s1.hashCode() );
System.out.println("Ea hashcode " + s2.hashCode() );
}
What about this?
public static void main(String[] args) {
String s1 = "FB";
String s2 = "Ea";
System.out.println( s1.equals(s2) );
System.out.println("Compassites " + s1.hashCode() );
System.out.println("Ea " + s2.hashCode() );
}
It Produces the following output.
false
FB hashcode 2236
Ea hashcode 2236
You can see that the hashcodes are same for “FB” and “Ea”. So we can
conclude that...
Two Rules:
1. If two objects are equal then they must have the same
hashcode. (hascode of “aa” and “aa” are same)
2. If two objects have the same hashcode, they may or may not
be equal. (string “FB” has hashcode 2236 and “Ea” has
hashcode 2236 bu they are not equal)
To make it 2nd point clear, we can say that
“Birthday as HashCode”
Now that we are aware of Hashcode and Equals method, let’s
learn the internal working of Hashmap
Hashing?
HashMap is known as HashMap because it uses a technique
called Hashing.
Hashing is a technique of converting a large String to small
String that represents same String.
A shorter value helps in indexing and faster searches.
Internally HashMap contains an array of Node and a node is
represented as a class which contains 4 fields :
It can be seen that node is containing a
reference of its own object. So it’s a linked
list.
Hashmap:
Few Terms...
Buckets : A bucket is one element of HashMap array. It is used to store nodes.
Two or more nodes can have the same bucket. In that case link list structure is
used to connect the nodes.
Load Factor is a measure, which decides when exactly to increase the hashmap
capacity(buckets).
HashMap() : It is the default constructor which creates an instance of HashMap
with initial capacity 16 and load factor of 0.75. (meaning capacity is doubled
when 75% of hashmap is filled)
HashMap(int initialCapacity, float loadFactor) : It creates a HashMap instance
with specified initial capacity and specified load factor.
.
Put Operation in HashMap:
Say our program is something like this
HashMap<String, Integer> map = new HashMap<>();
scores.put (“Rohit”, 140);
scores.put (“Dinesh”, 70);
scores.put (“Dhoni”, 90);
scores.put (“Kholi”, 100);
scores.put (“Sachin”, 150);
scores.put (“Dravid”, 130);
Let’s see what is happening internally...
Initially Empty hashMap:
Here, the hashmap’s size is 16.(default hashmapsize)
HashMap map = new HashMap();
Inserting Key-Value Pair:
Let us understand at which location below key value pair will be saved into HashMap.
scores.put (“Rohit”, 140);
When you call the put function then it computes the hash code of the Key.
Lets suppose the Hash code of (“Rohit”) is 2657860.
Our array has an index till 15, so in order to store “Rohit”, we have to calculate index using a modular operation
Index = 2657860 % 16 => 4
Index = 4, So 4 is the computed bucket index value where the entry will sit as a
node in the HashMap.
Hash Collision
Let us understand at which location below key value pair will be saved into HashMap.
scores.put (“Dhoni”, 90);
When you call the put function then it computes the hash code of the Key.
Lets suppose the Hash code of (“Dhoni”) is 63281940.
Our array has an index till 15, so in order to store “Rohit”, we have to calculate index using a
modular operation
Index = 63281940 % 16 => 4
Get Operation in HashMap:
int rohitScore = scores.get (“Rohit”);
So get operation does the same as that of put operation. When the get function is
called it basically gets the hash code of the Key.
Lets suppose Hash of (“Rohit”) is 2657860
Index = 2657860 % 16 => 4
Now hashMap lookups at bucket index 4 for the hash code of the key
“2657860”.
Hash code “2657860” found then it lookup for the Key “Rohit” itself in
that node or linked list.
Thank you :)

More Related Content

What's hot

What's hot (20)

Spring Core
Spring CoreSpring Core
Spring Core
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java IO
Java IOJava IO
Java IO
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java collections
Java collectionsJava collections
Java collections
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to How Hashmap works internally in java

Hashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.pptHashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.ppt
ssusere3b1a2
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
chidabdu
 

Similar to How Hashmap works internally in java (20)

Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Hashing data
Hashing dataHashing data
Hashing data
 
Data Structure and Algorithms: What is Hash Table ppt
Data Structure and Algorithms: What is Hash Table pptData Structure and Algorithms: What is Hash Table ppt
Data Structure and Algorithms: What is Hash Table ppt
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)
 
Hash table
Hash tableHash table
Hash table
 
Hashing.pptx
Hashing.pptxHashing.pptx
Hashing.pptx
 
Chapter 10: hashing data structure
Chapter 10:  hashing data structureChapter 10:  hashing data structure
Chapter 10: hashing data structure
 
Hashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.pptHashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.ppt
 
18 hashing
18 hashing18 hashing
18 hashing
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
 
Cryptography - Simplified - Hash Functions
Cryptography - Simplified - Hash FunctionsCryptography - Simplified - Hash Functions
Cryptography - Simplified - Hash Functions
 
Hash table in java
Hash table in javaHash table in java
Hash table in java
 
unit-1-dsa-hashing-2022_compressed-1-converted.pptx
unit-1-dsa-hashing-2022_compressed-1-converted.pptxunit-1-dsa-hashing-2022_compressed-1-converted.pptx
unit-1-dsa-hashing-2022_compressed-1-converted.pptx
 
Lecture notesmap
Lecture notesmapLecture notesmap
Lecture notesmap
 
Hashing 1
Hashing 1Hashing 1
Hashing 1
 
linear probing
linear probinglinear probing
linear probing
 
Algorithms notes tutorials duniya
Algorithms notes   tutorials duniyaAlgorithms notes   tutorials duniya
Algorithms notes tutorials duniya
 
Hashing
HashingHashing
Hashing
 
DS THEORY 35.pptx
DS THEORY 35.pptxDS THEORY 35.pptx
DS THEORY 35.pptx
 
Hash pre
Hash preHash pre
Hash pre
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

How Hashmap works internally in java

  • 2. Introduction HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java. It stores the data in (Key, Value) pairs.
  • 3. Equals and hashcode methods In order to understand the internal working of HashMap, we must be aware of hashcode and equals method. equals(Object otherObject) – As method name suggests, it is used to simply verify the equality of two objects. hashcode() – is a integer code generated for any variable/object after applying a formula/algorithm on its properties. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], where s[i] is the ith character of the string, n is the length of the string.
  • 4. What’s the output? public static void main(String[] args) { String s1 = "Compassites"; String s2 = "Software"; System.out.println( s1.equals(s2) ); System.out.println("Compassites " + s1.hashCode() ); System.out.println("Ea " + s2.hashCode() ); } It Produces the following output. false Compassites hashCode: 1297712907 Software hasCode: 1383974343
  • 5. What about this? public static void main(String[] args) { String s1 = "FB"; String s2 = "Ea"; System.out.println( s1.equals(s2) ); System.out.println("FB hashcode " + s1.hashCode() ); System.out.println("Ea hashcode " + s2.hashCode() ); }
  • 6. What about this? public static void main(String[] args) { String s1 = "FB"; String s2 = "Ea"; System.out.println( s1.equals(s2) ); System.out.println("Compassites " + s1.hashCode() ); System.out.println("Ea " + s2.hashCode() ); } It Produces the following output. false FB hashcode 2236 Ea hashcode 2236 You can see that the hashcodes are same for “FB” and “Ea”. So we can conclude that...
  • 7. Two Rules: 1. If two objects are equal then they must have the same hashcode. (hascode of “aa” and “aa” are same) 2. If two objects have the same hashcode, they may or may not be equal. (string “FB” has hashcode 2236 and “Ea” has hashcode 2236 bu they are not equal) To make it 2nd point clear, we can say that “Birthday as HashCode”
  • 8. Now that we are aware of Hashcode and Equals method, let’s learn the internal working of Hashmap
  • 9. Hashing? HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents same String. A shorter value helps in indexing and faster searches.
  • 10. Internally HashMap contains an array of Node and a node is represented as a class which contains 4 fields : It can be seen that node is containing a reference of its own object. So it’s a linked list. Hashmap:
  • 11. Few Terms... Buckets : A bucket is one element of HashMap array. It is used to store nodes. Two or more nodes can have the same bucket. In that case link list structure is used to connect the nodes. Load Factor is a measure, which decides when exactly to increase the hashmap capacity(buckets). HashMap() : It is the default constructor which creates an instance of HashMap with initial capacity 16 and load factor of 0.75. (meaning capacity is doubled when 75% of hashmap is filled) HashMap(int initialCapacity, float loadFactor) : It creates a HashMap instance with specified initial capacity and specified load factor.
  • 12. .
  • 13. Put Operation in HashMap: Say our program is something like this HashMap<String, Integer> map = new HashMap<>(); scores.put (“Rohit”, 140); scores.put (“Dinesh”, 70); scores.put (“Dhoni”, 90); scores.put (“Kholi”, 100); scores.put (“Sachin”, 150); scores.put (“Dravid”, 130); Let’s see what is happening internally...
  • 14. Initially Empty hashMap: Here, the hashmap’s size is 16.(default hashmapsize) HashMap map = new HashMap();
  • 15. Inserting Key-Value Pair: Let us understand at which location below key value pair will be saved into HashMap. scores.put (“Rohit”, 140); When you call the put function then it computes the hash code of the Key. Lets suppose the Hash code of (“Rohit”) is 2657860. Our array has an index till 15, so in order to store “Rohit”, we have to calculate index using a modular operation Index = 2657860 % 16 => 4 Index = 4, So 4 is the computed bucket index value where the entry will sit as a node in the HashMap.
  • 16.
  • 17. Hash Collision Let us understand at which location below key value pair will be saved into HashMap. scores.put (“Dhoni”, 90); When you call the put function then it computes the hash code of the Key. Lets suppose the Hash code of (“Dhoni”) is 63281940. Our array has an index till 15, so in order to store “Rohit”, we have to calculate index using a modular operation Index = 63281940 % 16 => 4
  • 18.
  • 19. Get Operation in HashMap: int rohitScore = scores.get (“Rohit”); So get operation does the same as that of put operation. When the get function is called it basically gets the hash code of the Key. Lets suppose Hash of (“Rohit”) is 2657860 Index = 2657860 % 16 => 4 Now hashMap lookups at bucket index 4 for the hash code of the key “2657860”. Hash code “2657860” found then it lookup for the Key “Rohit” itself in that node or linked list.