The Wayback Machine - https://web.archive.org/web/20241001021916/https://www.geeksforgeeks.org/internal-working-of-hashmap-java/
Open In App

Internal Working of HashMap in Java

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will see how the HashMap get and put method works internally. What operations are performed? How the hashing is done. How the value is fetched by key. How the key-value pair is stored.
In the previous article, HashMap contains an array of Node and Node can represent a class having the following objects : 

  1. int hash
  2. K key
  3. V value
  4. Node next

Now we will see how this works. First, we will see the hashing process. 

Hashing

Hashing is a process of converting an object into integer form by using the method hashCode(). It’s necessary to write the hashCode() method properly for better performance of HashMap. Here, we are taking the key of my class so that we can override the hashCode() method to show different scenarios. Our Key class is: 

//custom Key class to override hashCode()
// and equals() method
class Key
{
  String key;
  Key(String key)
  {
    this.key = key;
  }
  
  @Override
  public int hashCode() 
  {
     return (int)key.charAt(0);
  }

  @Override
  public boolean equals(Object obj)
  {
    return key.equals((String)obj);
  }
}

Here override hashCode() method returns the first character’s ASCII value as hash code. So whenever the first character of the key is same, the hash code will be the same. You should not approach these criteria in your program. It is just for demo purposes. As HashMap also allows a null key, so hash code of null will always be 0.

hashCode() method:

hashCode() method is used to get the hash code of an object. hashCode() method of the object class returns the memory reference of an object in integer form. Definition of hashCode() method is public native hashCode(). It indicates the implementation of hashCode() is native because there is not any direct method in Java to fetch the reference of the object. It is possible to provide your implementation of hashCode(). 
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. 

Syntax:

public int hashCode() {    

// Implementation to calculate and return the hash code

}

The hashCode() method in Java does not take any parameters explicitly. Its purpose is to the return an integer hash code value that represents the object’s identity or contents.

Example of hashCode():

Java
import java.util.HashMap;

public class HashCodeExample {

    public static void main(String[] args) {
        // Creating objects
        Student student1 = new Student(1, "Alice");
        Student student2 = new Student(2, "Bob");
        Student student3 = new Student(1, "Alice");        
        // Creating a HashMap
        HashMap<Student, String> studentMap = new HashMap<>();       
        // Adding elements to the HashMap
        studentMap.put(student1, "A Grade");
        studentMap.put(student2, "B Grade");        
        // Retrieving elements from the HashMap
        System.out.println("Grade of student1: " + studentMap.get(student1)); 
        System.out.println("Grade of student2: " + studentMap.get(student2));        
        // Using student3 to retrieve a value
        System.out.println("Grade of student3: " + studentMap.get(student3)); 
    }
}
// Student class with overridden hashCode and equals methods
class Student {
    private int id;
    private String name;
    // Constructor
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    // Override hashCode method
    @Override
    public int hashCode() {
        // Generate hashCode based on id and name
        int result = 17;
        result = 31 * result + id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
    // Override equals method for the HashMap key comparison
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        if (id != student.id) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }
}

output :

Grade of student1: A Grade
Grade of student2: B Grade
Grade of student3: A Grade

Explanation of the above Program:

  • The program demonstrates how to correctly implement hashCode and equals methods in a custom Student class to ensure proper behavior in a HashMap.
  • By overriding these methods, the program ensures that two Student objects with the same id and name are considered equal and produce the same hash code, allowing consistent retrieval of values associated with these keys from the HashMap.

equals() method:

This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. 
HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. 

Syntax:

public boolean equals(Object obj) {    

// Implementation to compare the current object with another object

}

The equals() method takes an object as a parameter and returns a boolean indicating whether the current object is equal to the provided object.

Buckets:

A bucket is an element of the HashMap array. It is used to store nodes. Two or more nodes can have the same bucket. In that case, a link list structure is used to connect the nodes. Buckets are different in capacity. A relation between bucket and capacity is as follows: 

capacity = number of buckets * load factor

A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized. 

Index Calculation in Hashmap

Generated hash code may be in the range of integer and if we create arrays for such a range, then it will easily cause outOfMemoryException. So we generate an index to minimize the size of the array. The following operation is performed to calculate the index. 

index = hashCode(key) & (n-1).

Where, n is the number of buckets or the size of the array. In our example, I will consider n as the default size which is 16. 

Why the above method is used to calculate the index

Using a bitwise AND operator is similar to doing bit masking wherein only the lower bits of the hash integer is considered which in turn provides a very efficient method of calculating the modulus based on the length of the hashmap.

  • Initially Empty hashMap: Here, the hashmap’s size is taken as 16.  
HashMap map = new HashMap();
  • HashMap: 
     
Hashmap working


  • Inserting Key-Value Pair: Putting one key-value pair in the above HashMap 
map.put(new Key("vishal"), 20);
  • Steps: 
    1. Calculate hash code of Key {“vishal”}. It will be generated as 118.
    2. Calculate index by using index method it will be 6.
    3. Create a node object as : 
{
  int hash = 118

  // {"vishal"} is not a string but 
  // an object of class Key
  Key key = {"vishal"}

  Integer value = 20
  Node next = null
}
  1. Place this object at index 6, if no other object is presented there.
  • Inserting another Key-Value Pair: Now, putting the other pair that is, 
map.put(new Key("sachin"), 30);
  • Steps:
    1. Calculate hashCode of Key {“sachin”}. It will be generated as 115.
    2. Calculate index by using index method it will be 3.
    3. Create a node object as : 
       
{
  int hash = 115
  Key key = {"sachin"}
  Integer value = 30
  Node next = null
}
  • In Case of collision: Now, putting another pair that is, 
     
map.put(new Key("vaibhav"), 40);
  • Steps: 
    1. Calculate hash code of Key {“vaibhav”}. It will be generated as 118.
    2. Calculate index by using index method it will be 6.
    3. Create a node object as :
 {
  int hash = 118
  Key key = {"vaibhav"}
  Integer value = 40
  Node next = null
}
  1. Place this object at index 6 if no other object is presented there.
  2. In this case, a node object is found at index 6 – this is a case of collision.
  3. In that case, check via the hashCode() and equals() method if both the keys are the same.
  4. If keys are the same, replace the value with the current value.
  5. Otherwise, connect this node object to the previous node object via linked list and both are stored at index 6. 
    Now HashMap becomes :

3_hasharray


 

Using the get method()

Now let’s try some get methods to get a value. get(K key) method is used to get a value by its key. If you don’t know the key then it is not possible to fetch a value. 

  • Fetch the data for key sachin:
map.get(new Key("sachin"));
  • Steps: 
    1. Calculate hash code of Key {“sachin”}. It will be generated as 115.
    2. Calculate index by using index method it will be 3.
    3. Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.
    4. In our case, it is found as the first element and the returned value is 30.
  • Fetch the data for key vaibhav: 
map.get(new Key("vaibhav"));
  • Steps: 
    1. Calculate hash code of Key {“vaibhav”}. It will be generated as 118.
    2. Calculate index by using index method it will be 6.
    3. Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.
    4. In our case, it is not found as the first element and the next node object is not null.
    5. If the next node is null then return null.
    6. If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.
    7. Time complexity is almost constant for the put and the get method until rehashing is not done.
    8. In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.
    9. If the key given already exist in HashMap, the value is replaced with the new value.
    10. hash code of the null key is 0.
    11. When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field.


Similar Reads

Internal Working of ArrayList in Java
ArrayList is a resizable array implementation in Java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object classes. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is tra
10 min read
Internal working of Set/HashSet in Java
As we know that a set is a well-defined collection of distinct objects. Each member of a set is called an element of the set. So in other words, we can say that a set will never contain duplicate elements. But how in java Set interface implemented classes like HashSet, LinkedHashSet, TreeSet etc. achieve this uniqueness. In this post, we will discu
3 min read
Java Swing | Internal Frame with examples
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with n
8 min read
HashMap clear() Method in Java
The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Syntax: Hash_Map.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate the working of java.util.HashMap.clear() Method:
2 min read
HashMap containsKey() Method in Java
The java.util.HashMap.containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map. Syntax: Hash_Map.containsKey(key_element) Parameters: The method takes just one parameter key_element that refers to the key whos
2 min read
HashMap clone() Method in Java
Let us do clear out the foundation concept of shallow copy and deep copy in java. Shallow repetition is quicker. However, it’s “lazy” it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each the first and therefore the copy can h
3 min read
HashMap containsValue() Method in Java
The java.util.HashMap.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map. Syntax: Hash_Map.containsValue(Object Value) Parameters: The method takes just one paramete
2 min read
HashMap isEmpty() Method in Java
The java.util.HashMap.isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False. Syntax: Hash_Map.isEmpty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the map is empty or does not
2 min read
HashMap entrySet() Method in Java
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them. Syntax: hash_map.entrySet() Parameters: The method does not take any parameter. Return Value: The method returns
2 min read
HashMap get() Method in Java
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: Hash_Map.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the key whose
2 min read
HashMap keySet() Method in Java
The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Syntax: hash_map.keySet() Parameters: The method does not take any parameter. Return Value: The method returns a set havin
2 min read
HashMap size() Method in Java
The java.util.HashMap.size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Syntax: Hash_Map.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in t
2 min read
HashMap put() Method in Java
The java.util.HashMap.put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole. Syntax: Hash_Map.put
3 min read
HashMap putAll() Method in Java
The java.util.HashMap.putAll() is an inbuilt method of HashMap class that is used for the copy operation. The method copies all of the elements i.e., the mappings, from one map into another. Syntax: new_hash_map.putAll(exist_hash_map) Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from. Ret
2 min read
HashMap remove() Method in Java
The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax: Hash_Map.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The
2 min read
HashMap values() Method in Java
The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters. Return Value: The method is used to return a collection view containing all
2 min read
HashMap compute() method in Java with Examples
The compute(Key, BiFunction) method of HashMap class allows you to update a value in HashMap. The compute() method tries to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to automatically update a value for given key in HashMap. If the remapping function pa
4 min read
How to check if a key exists in a HashMap in Java
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient): Get the HashMap and the Key Create an iterator to iterate over the
4 min read
Difference Between ArrayList and HashMap in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java's collection since Java 1.2. It provides the basic implementation o
7 min read
HashMap replace(key, oldValue, newValue) method in Java with Examples
The replace(K key, V oldValue, V newValue) method of Map interface, implemented by HashMap class is used to replace the old value of the specified key only if the key is previously mapped with the specified old value. Syntax: default boolean replace(K key, V oldValue, V newValue) Parameters: This method accepts three parameters : key: which is the
3 min read
HashMap replace(key, value) method in Java with Examples
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Syntax: public V replace(K key, V value) Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced. value:
3 min read
HashMap putIfAbsent(key, value) method in Java with Examples
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance. Syntax: public V putIfAbsent(K key, V value)Parameters: This method accepts two parameters: key: which is the key with which provided value has to be mapped.va
3 min read
HashMap forEach(BiConsumer) method in Java with Examples
The forEach(BiConsumer) method of HashMap class perform the BiConsumer operation on each entry of hashmap until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until a
3 min read
HashMap merge(key, value, BiFunction) method in Java with Examples
The merge(Key, Value, BiFunctional) method of the HashMap class is used to combine multiple mapped values for a key using the given mapping function. A bucket is actually an index of the array, that array is called a table in HashMap implementation. So table[0] is referred to as bucket0, table[1] as bucket1, and so on. If the key is not present or
3 min read
HashMap getOrDefault(key, defaultValue) method in Java with Examples
The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned. Syntax: default V getOrDefault(Object key, V defaultValue) Parameters: This method accepts two parameters: key: which i
2 min read
HashMap computeIfPresent(key, BiFunction) method in Java with Examples
The computeIfPresent(Key, BiFunction) method of HashMap class which allows you to compute value of a mapping for specified key if key is already associated with a value (or is mapped to null). If mapping function of this method returns null, the mapping is removed. If the remapping function throws an exception, the exception is rethrown, and the ma
2 min read
HashMap replaceAll(BiFunction) method in Java with Examples
The replaceAll(BiFunction) method of HashMap class replaces each value with the result of applying the given function(performs a certain operation) on the corresponding value. This process continues in the same manner until all the entries have been processed or until an exception is thrown by the function. It rethrows exceptions thrown by the repl
3 min read
How to Convert HashMap to ArrayList in Java?
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. Unlike Hashmap, an ArrayList is used to provides us with dynamic arrays in Java. It is an alternative to an array that provides a lot more flexibility in terms of storage. In this articl
5 min read
Difference between HashMap and IdentityHashMap in Java
HashMap in java is a class that is a part of the java collection. It implements the Map interface of java. It stores the data in the form of key and value pair. The key should be unique but the value may be duplicate. If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to the hash table,
4 min read
How to Convert Map to JSON to HashMap in Java?
JSON is an open standard file format, and easier data interchange format helpful for humans to transmit data. Most of the apps display JSON data and hence nowadays JSON has become the mandatory media to transmit data. Here we will get to know how to convert Map to JSON and for Map, let us take HashMap as an input set of data. Installation: Step 1:
8 min read
Article Tags :
Practice Tags :