Tuesday , March 28 2017
Home / java / How HashMap Works In Java

How HashMap Works In Java

HashMap is one of the classes in the Collections framework. Before examining how HashMap works, let us understand how maps and hash tables work.

What is a Map?

Maps provide a way to store key/value pairs. In Java, a map is an object that contains key/value associations. While both keys and values are objects, keys must be unique whereas values need not be unique. Keys are used to identify and retrieve values from a map. Java provides the functionality to work with maps through the Map interface. The get () and put () methods in the Map interface are used to retrieve a value from a map and to store a value into a map respectively.

The Map interface is one of the interfaces in the Collections framework. Several classes in the Collections framework implement this interface. The AbstractMap class is one such class that provides a basic implementation of the Map interface. The HashMap class extends the AbstractMap class and provides an implementation of the Map interface through a hash table.

Hash Table

A hash table is a data structure that stores key/value mappings. The primary purpose of a hash table is fast storage and retrieval of data by using unique keys that map to values. The key/value pairs in a hash table are stored in buckets. A bucket is a simple linked list that stores objects. In a hash table, data is stored using a mechanism called hashing. This mechanism uses a hash function to determine the location where a value is to be stored or retrieved.

The HashMap Class

In Java, the HashMap class stores maps in hash tables. HashMap is a generic class that implements the Map interface and has the following declaration:

class HashMap<K,V>

In this declaration, K indicates the type of keys and V indicates the type of values in the map.


HashMap<String, Float> hm = new HashMap<String, Float>();

The HashMap class allows the use of null values and null keys. It is unsynchronized and the order of the map in a hash table does not remain constant. The HashMap class uses the hashCode() method as its hash function.

A HashMap instance has two parameters, namely, initial capacity and load factor.

Initial capacity: is the capacity of the HashMap instance at the time of creation. It denotes the number of buckets assigned to the hash table for data storage.

Load factor: specifies the maximum limit of the hash table at which the current capacity of the hash table needs to be increased.

The automatic mechanism that increases the capacity of a hash table is called rehashing. The initial capacity and load factor are important because too many rehash operations affect the performance of the hash table. Therefore, care must be taken to set optimal initial capacity and load factor.

Note: The HashMap class provides constant-time performance for the get and put operations. If its granted that the hash function stores the elements evenly across buckets, the time complexity of the operations in a HashMap instance is O(1).

The default initial capacity and load factor of a HashMap instance are 16 and 0.75 respectively. While creating a HashMap instance, you can either specify values for the initial capacity and load factor or allow Java to use the default values. The following table lists the constructors in the HashMap class:



A default hash map with 16 as the initial capacity and 0.75 as the load factor.

HashMap(Map<? extends K, ? extends V>m)

A hash map with the mappings specified by Map and initializes it using the elements of m.

HashMap(int initialCapacity)

A hash map with the initial capacity specified by the initialCapacity parameter and 0.75 load factor.

HashMap(int initialCapacity, float loadFactor)

A hash map with the initial capacity specified by the initialCapacity parameter and the load factor specified by the loadFactor parameter.


The following program is an example that uses a HashMap instance to store customer names and account balance information.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapExample {

    public static void main(String args[]) {
        HashMap<String, Double> hm = new HashMap<String, Double>();

        hm.put("Jason Smith", new Double(2325.34));
        hm.put("Joey Williams", new Double(553.52));
        hm.put("Angelina Johnson", new Double(658.25));
        hm.put("Tedd Wilson", new Double(100.50));
        hm.put("Katherine Hunt", new Double(-18.28));

        Set<Map.Entry<String, Double>> set = hm.entrySet();
        for (Map.Entry<String, Double> me : set) {
            System.out.print(me.getKey() + ": ");

        double balance = hm.get("Angelina Johnson");
        hm.put("Angelina Johnson", balance + 500);
        System.out.println("Angelina Johnson's new balance: "
                + hm.get("Angelina Johnson"));
Jason Smith: 2325.34
Angelina Johnson: 658.25
Tedd Wilson: 100.5
Katherine Hunt: -18.28
Joey Williams: 553.52

Angelina Johnson's new balance: 1158.25

In this example, hm is a HashMap instance that stores customer name and account balance as a key/value pair of string and double values. By using the put() method, the keys and values are stored into the hash table.

The entrySet() method is used to obtain a set-view of the hash map. The result of this method is a set of elements that contain the HashMap entries. Each element in this set is an object of the Map.Entry interface. The program uses a for each loop with the getKey() and getValues() methods to display all the map entries and then updates the value in Angelina Johnson’s account.

Key points

  1. HashMap is fast.
  2. HashMap accepts the null.
  3. HashMap stores key along with the value pairs.
  4. Easy to use the HashMap functionality.
  5. Easy for looking the code on the Open JDK or Java source.
  6. HashMap works on the principle of hashing.
  7. We can get(key) method and put(key, value) to store and retrieve Objects from the HashMap.
  8. When passing the Key as well as the Value object.
  9. To put() method for the Java HashMap, then the HashMap can also give the calls hashCode method for the Key object.
  10. Storing the Entry object that can be useful for the bucket location and the HashMap can be useful for the key and value object along with the Map.Entry.

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Type Inference in Java 7 Example

Type Inference in Java 7 is another great addition introduced to ease the developer to type …

Leave a Reply

Your email address will not be published. Required fields are marked *