🌐
GeeksforGeeks
geeksforgeeks.org › java › internal-working-of-hashmap-java
Internal Working of HashMap in Java - GeeksforGeeks
May 25, 2026 - It provides average O(1) time complexity for basic operations. It is not thread-safe and allows one null key and multiple null values. Internally, a HashMap is implemented as an array of nodes, where each node stores a key-value pair.
🌐
Medium
medium.com › @yashodhara.chowkar › internal-working-of-hashmap-in-java-and-performance-improvement-in-java-8-a28ee1660cda
Internal Working of HashMap in Java and Performance Improvement in Java 8 | by Yashodhara C H | Medium
May 14, 2024 - In Java, the HashMap class is a component of the Java Collections Framework and resides within the java.util package. It serves as the standard implementation of the Map interface. A HashMap organizes data in the form of key and a value pair ...
Discussions

Is HashMap internally implemented in Java using LinkedList or Array? - Stack Overflow
How is HashMap internally implemented? I read somewhere that it uses LinkedList while other places it mentions Arrays. I tried studying the code for HashSet and found Entry array. Then where is More on stackoverflow.com
🌐 stackoverflow.com
Java Hashmap - Please explain how hash maps work - Stack Overflow
In a Map, there is only one value for a key -- if you put a new value for the same key, the old value will be replaced. HashMaps are implemented using 'buckets' -- an array of cells of finite size, indexed by the hashCode of the key. More on stackoverflow.com
🌐 stackoverflow.com
MOOC Part 12: Creating your own implementation of a HashMap
For my data structures class, we had to build our own array-based hash map. Best I can explain what I know is that you’re putting hashed key-value pairs into the array. Let’s say the initial length of the backing array is 5 and the load factor is .75 like you say. That means on the 4th add (4/5 > .75) the array will be resized into a new array (my class used 2*length +1 for this operation, something about prime numbers reduce the chances of hashing collisions) and all the values will be rehashed. Then if you assume a number’s hash code is itself for simplicity (I don’t understand how the actual .hashcode() method works internally, generates some big number), start by adding 11 to the hashmap. The haschode is 11, and that’s not a valid index value in the map. What we’d do is always % by the length of the map. 11%5 = 1, so check the hash map to see if there’s anything at index 1, there’s not, so add it there. Then you’d add let’s say 7. 7%5 is 2, there’s nothing in the map at 2, so you add 7 at 2. Backing array rn would look something like this [null, 11, 7, null, null] Then let’s say you add 16 to the map. 16%5 is 1, so you try and add it at index 1. There is already a value there, this is called a collision. There are a couple ways of dealing with this, I think linear probing is probably the most basic, but you can look into chaining too, basically creates a linked list at each index so you’d add 16 to 11’s next pointer. But with linear probing you’d see that there is a value there, so you’d move to the next index. You’d see that there is also a value there (7) so you’d again move to the next index. Now you’re at index 3, there’s nothing there, you’d put 16 there and your backing array would look like [null, 11, 7, 16 null] Notice the num of items in there / total spots (3/5) is still less than .75 Then let’s say you add 10. The condition where size / array.length() >.75 is trigged and the resizeArray method is called. For my class we’d resize this to 2*length+1, so the new array size would be 11. Now you’d iterate through the original and add the elements to the new spot in the new backing array. So, 11 % 11 = 0 (11 at index 0), 7 % 11= index 7, 16%11 = index 5, and now you add 10 (10%11= 10.) So your new resized backingArray would be [11, null, null, null, null, 16, null, 7, null, null, 10, null] A collision could occur there too though so you have to make sure to include a way of handling that in there. And then I forgot to mention but in adding you also have to check if the actual keys are the same, in which case you’d update the key with the new value you’re adding in because hash maps can’t have duplicate keys. Removing can be a little tricky but there’s tons on YouTube about it, if you find the pair you’re looking for in the map if you’re using linear probing as the collision method you sometimes have to set a marker on the index you’re removing from so it doesn’t affect a later search method. Hope all that helps and there’s plenty of stuff out there too to help with coding all that once you’re actually implementing it, good luck M8. And re firstFreeIndex, I haven’t seen that before but it looks like a more efficient way to do linear probing. In my class we’d manually iterate until we found an empty spot in the HashMap to add the pair, but that would be O(n) in worst cases and having firstFreeIndex keep track of that index seems helpful. So if there was a collision you would just put your pair at firstFreeIndex rather than iterating until you find an empty space, that’s my impression of it at least More on reddit.com
🌐 r/learnjava
3
10
March 12, 2022
i wanna implement a hash map without importing it from the standard java library
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
12
4
May 31, 2022
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › HashMap.html
HashMap (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits ...
🌐
Turing
turing.com › kb › implementing-hashmap-in-java
How to Implement HashMap in Java from Scratch
By following the steps outlined ... lists. You can add key-value pairs to the HashMap using the put method, retrieve values using the get method, and remove key-value pairs using the remove method....
🌐
LinkedIn
linkedin.com › pulse › hashmap-custom-implementation-java-harshit-anand-e4e6c
HashMap Custom Implementation in Java
Login to LinkedIn to keep in touch with people you know, share ideas, and build your career.
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-hashmap-works-in-java.html
How HashMap works in Java?
In many cases, interviewee fails at this stage because they get confused between hashCode() and equals() or keys and values object in Java HashMap which is pretty obvious because they are dealing with the hashcode() in all previous questions and equals() come in the picture only in case of retrieving value object from HashMap in Java. Good and experienced Java developer will point out here that using an immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap keys and improve the performance of Java HashMap by reducing collision.
🌐
DZone
dzone.com › data engineering › data › java hashmap implementation in a nutshell
Java HashMap Implementation in a Nutshell
October 8, 2018 - In this tutorial, we demonstrate how to implement a custom HashMap in Java by using an array of an linked list, as well as inserting and retrieving elements.
Find elsewhere
🌐
LeetCode
leetcode.com › problems › design-hashmap
Design HashMap - LeetCode
Design HashMap - Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class: * MyHashMap() initializes the object with an empty map. * void put(int key, int value) inserts a (key, value) pair into the HashMap.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › the java hashmap under the hood
The Java HashMap Under the Hood
November 6, 2023 - Thus, if we plan to store ten elements in a HashMap, we must adjust it by the load factor. We can use a simple formula: divide the expected mappings by a load factor and add one. This solution isn’t perfect, as it allocates more space when the number of mappings is divisible by three. However, it’s quite simple to remember and understand. Java 19 provides a better solution to this problem and provides static factory HashMap.newHashMap, which accepts the number of mappings instead of capacity.
🌐
freeCodeCamp
freecodecamp.org › news › how-java-hashmaps-work-internal-mechanics-explained
How Java HashMaps Work – Internal Mechanics Explained
August 9, 2024 - The HashMap is fundamentally based on a hash table implementation, and its performance depends on two key parameters: initial capacity and load factor. The original javadocs of the Hash table class define these two parameters as follows:
🌐
CodeSignal
codesignal.com › learn › courses › hashing-dictionaries-and-sets-in-java › lessons › diving-into-hashmaps-understanding-implementation-and-complexity-analysis-in-java
Diving into HashMaps: Understanding Implementation and ...
HashMaps do not guarantee any specific map order; in other words, the order can change over time. HashMaps function using the principle of hashing. Here, a key is rendered to a hash code by a hash function, and this numeric code identifies the storage location for the key-value pair.
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
A HashMap stores items in key/value pairs, where each key maps to a specific value. It is part of the java.util package and implements the Map interface.
🌐
NareshIT
nareshit.com › blogs › hashmap-internal-working-in-java-step-by-step-guide-nareshit
HashMap Internal Working in Java: Step-by-Step Guide | NareshIT
Because HashMap relies on hashCode to find the bucket and equals to confirm key equality. Poor implementations can lead to incorrect behavior and bad performance. For comprehensive learning, consider a Java full stack developer course in Hyderabad to master these concepts.
Top answer
1 of 4
6

You're confusing the behaviour of a Map with the implementation of a HashMap.

In a Map, there is only one value for a key -- if you put a new value for the same key, the old value will be replaced.

HashMaps are implemented using 'buckets' -- an array of cells of finite size, indexed by the hashCode of the key.

It's possible for two different keys to hash to the same bucket, a 'hash collision'. In case of a collision, one solution is to put the (key, value) pairs into a list, which is searched when getting a value from that bucket. This list is part of the internal implementation of the HashMap and is not visible to the user of the HashMap.

This is probably what you are thinking of.

2 of 4
3

Your basic understanding is correct: maps in general and hashmaps in particular only support one value per key. That value could be a list but that's something different. put("a", 2) will replace any value for key "a" that's already in the list.

So what are you missing?

Every explanation says that in case there is more than a single value per key, the values are being linked listed to the bucket.

Yes, that's basically the case (unless the list is replaced by a tree for efficiency reasons but let's ignore that here).

This is not about putting values for the same key into a list, however, but for the same bucket. Since keys could be mapped to the same bucket due to their hash code you'd need to handle that "collision".

Example:

Key "A" has a hash code of 65, key "P" has a hash code of 81 (assuming hashCode() just returns the ascii codes).

Let's assume our hashmap currently has 16 buckets. So when I put "A" into the map, which bucket does it go to? We calculate bucketIndex = hashCode % numBuckets (so 65 % 16) and we get the index 1 for the 2nd bucket.

Now we want to put "P" into the map. bucketIndex = hashCode % numBuckets also yields 1 (81 % 16) so the value for a different key goes to the same bucket at index 1.

To solve that a simple implementation is to use a linked list, i.e. the entry for "A" points to the next entry for "P" in the same bucket.

Any get("P") will then look for the bucket index first using the same calculation, so it gets 1. Then it iterates the list and calls equals() on each entry's key until it hits the one that matches (or none if none match).

🌐
Reddit
reddit.com › r/learnjava › mooc part 12: creating your own implementation of a hashmap
r/learnjava on Reddit: MOOC Part 12: Creating your own implementation of a HashMap
March 12, 2022 -

Okay, so I'm currently on part 12 of the University of Helsinki's MOOC. This whole section about creating your own List and HashMap implementation is really interesting, and I want to grasp all the concepts correctly.

So a HashMap is basically an array that contains lists where the pairs are stored? I think I got that correctly... But still not sure.

And when you want to add a new pair, you have to generate a hashvalue that should be inside the extension of the array but also randomized from the hashcode of the key of the pair itself so that it somehow ends up in whatever list of the array so that it's a bit more evenly distributed across the entire array of lists? (not sure if I'm actually saying something real there lol, but I do think that the randomness of the hashvalue obtained has to do with something about the pairs not accumulating on a particular list of the array).

I'm also trying to understand the relationships between the grow(), copy() and add() methods that are proposed. If I understand correctly, add() checks for the space and if the array is more than 75% full then it calls grow(), creating a bigger array, and then copy() which basically reassings new hashvalues to each pair that is already present on each of the lists inside the array but with the bigger space now added in the formula to get it.

I'm a bit confused on the role that the variable firstFreeIndex takes here as well. It seems to be increased every single time a new pair is added... Meaning that it doesn't really care about what list in the array that pair went, but it is rather a representation of how much space is theoretically taken by each new pair. And then it gets to a point where that theoretical space needs to be expanded so that the evenly distributed pairs inside the lists of the array have a bigger space where it is harder for them to get a hashcode collision? (The collisions are a topic I stumbled upon while doing research about all of this too).

Sorry if this is too long, and if I messed up the entire point somewhere, but this is the topic that has had me the most intrigued and confused out of all the mooc so far...

Top answer
1 of 2
4
For my data structures class, we had to build our own array-based hash map. Best I can explain what I know is that you’re putting hashed key-value pairs into the array. Let’s say the initial length of the backing array is 5 and the load factor is .75 like you say. That means on the 4th add (4/5 > .75) the array will be resized into a new array (my class used 2*length +1 for this operation, something about prime numbers reduce the chances of hashing collisions) and all the values will be rehashed. Then if you assume a number’s hash code is itself for simplicity (I don’t understand how the actual .hashcode() method works internally, generates some big number), start by adding 11 to the hashmap. The haschode is 11, and that’s not a valid index value in the map. What we’d do is always % by the length of the map. 11%5 = 1, so check the hash map to see if there’s anything at index 1, there’s not, so add it there. Then you’d add let’s say 7. 7%5 is 2, there’s nothing in the map at 2, so you add 7 at 2. Backing array rn would look something like this [null, 11, 7, null, null] Then let’s say you add 16 to the map. 16%5 is 1, so you try and add it at index 1. There is already a value there, this is called a collision. There are a couple ways of dealing with this, I think linear probing is probably the most basic, but you can look into chaining too, basically creates a linked list at each index so you’d add 16 to 11’s next pointer. But with linear probing you’d see that there is a value there, so you’d move to the next index. You’d see that there is also a value there (7) so you’d again move to the next index. Now you’re at index 3, there’s nothing there, you’d put 16 there and your backing array would look like [null, 11, 7, 16 null] Notice the num of items in there / total spots (3/5) is still less than .75 Then let’s say you add 10. The condition where size / array.length() >.75 is trigged and the resizeArray method is called. For my class we’d resize this to 2*length+1, so the new array size would be 11. Now you’d iterate through the original and add the elements to the new spot in the new backing array. So, 11 % 11 = 0 (11 at index 0), 7 % 11= index 7, 16%11 = index 5, and now you add 10 (10%11= 10.) So your new resized backingArray would be [11, null, null, null, null, 16, null, 7, null, null, 10, null] A collision could occur there too though so you have to make sure to include a way of handling that in there. And then I forgot to mention but in adding you also have to check if the actual keys are the same, in which case you’d update the key with the new value you’re adding in because hash maps can’t have duplicate keys. Removing can be a little tricky but there’s tons on YouTube about it, if you find the pair you’re looking for in the map if you’re using linear probing as the collision method you sometimes have to set a marker on the index you’re removing from so it doesn’t affect a later search method. Hope all that helps and there’s plenty of stuff out there too to help with coding all that once you’re actually implementing it, good luck M8. And re firstFreeIndex, I haven’t seen that before but it looks like a more efficient way to do linear probing. In my class we’d manually iterate until we found an empty spot in the HashMap to add the pair, but that would be O(n) in worst cases and having firstFreeIndex keep track of that index seems helpful. So if there was a collision you would just put your pair at firstFreeIndex rather than iterating until you find an empty space, that’s my impression of it at least
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
GitHub
github.com › contactsunny › HashMap_Implementaion_Java_POC
GitHub - contactsunny/HashMap_Implementaion_Java_POC: This is a simple example of a hash map implementation in Java. · GitHub
We create a custom Node class which can take keys and values of generic type K, V, so that we can create maps of different types using the same implementation class. We also create a HashMap class which will hold the actual nodes of the hash map.
🌐
Medium
medium.com › @mrinalgupta › internal-implementation-of-hashmap-bd739e231ca5
Internal Implementation of HashMap | by Mrinal Gupta | Medium
October 5, 2023 - We already know that the HashMap stores key-value pairs. HashMap has a nested static class called Node as shown below. static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; //some more code
🌐
Programiz
programiz.com › java-programming › examples
Java Examples | Programiz
Java Program to Implement the queue data structure · Java Program to Get the middle element of LinkedList in a single iteration · Java Program to Convert the LinkedList into an Array and vice versa · Java Program to Convert the ArrayList into a string and vice versa · Java Program to Iterate over an ArrayList · Java Program to Iterate over a HashMap ·