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

collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptxSameerAhmed593310
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 

What's hot (20)

collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Hash map
Hash mapHash map
Hash map
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java collection
Java collectionJava collection
Java collection
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 

Similar to How Hashmap works internally in java

Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptxAgonySingh
 
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 pptJUSTFUN40
 
Data Structures : hashing (1)
Data Structures : hashing (1)Data Structures : hashing (1)
Data Structures : hashing (1)Home
 
Hashing.pptx
Hashing.pptxHashing.pptx
Hashing.pptxkratika64
 
Chapter 10: hashing data structure
Chapter 10:  hashing data structureChapter 10:  hashing data structure
Chapter 10: hashing data structureMahmoud Alfarra
 
18 hashing
18 hashing18 hashing
18 hashingdeonnash
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashingchidabdu
 
Cryptography - Simplified - Hash Functions
Cryptography - Simplified - Hash FunctionsCryptography - Simplified - Hash Functions
Cryptography - Simplified - Hash FunctionsAbdul Manaf Vellakodath
 
Hash table in java
Hash table in javaHash table in java
Hash table in javasiriindian
 
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.pptxBabaShaikh3
 
Algorithms notes tutorials duniya
Algorithms notes   tutorials duniyaAlgorithms notes   tutorials duniya
Algorithms notes tutorials duniyaTutorialsDuniya.com
 
Hashing and separate chain
Hashing and separate chainHashing and separate chain
Hashing and separate chainVijayapriyaPandi
 

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
 
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
 
Hashing and separate chain
Hashing and separate chainHashing and separate chain
Hashing and separate chain
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

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.