What Is HashMap in Data Structure With Example?


Heather Bennett

What Is HashMap in Data Structure With Example?

A HashMap is a data structure that provides a way to store and retrieve key-value pairs. It is also known as a hash table.

In other programming languages, it may be referred to as an associative array or dictionary. The HashMap implementation in Java is part of the java.util package and is widely used due to its efficiency and versatility.

How Does HashMap Work?

A HashMap internally uses an array of buckets, where each bucket can store multiple key-value pairs. When you insert a key-value pair into the HashMap, it calculates the hash code of the key using the hashCode() method.

The hash code determines the index in the array where the pair will be stored.

If two different keys have the same hash code, called a hash collision, the HashMap uses a mechanism called chaining. Chaining means that multiple entries with different keys can be stored at the same index in the bucket, forming a linked list.

When retrieving a value by its key, HashMap iterates over this linked list to find the correct entry.

HashMap Example:

Let’s consider an example where we want to store information about students in a class using their roll numbers as keys and their names as values.

import java.util.HashMap;

public class StudentExample {
    public static void main(String[] args) {
        // Create a new HashMap
        HashMap studentMap = new HashMap<>();

        // Add student details
        studentMap.put(1, "John");
        studentMap.put(2, "Mary");
        studentMap.put(3, "Alice");

        // Retrieve values using keys
        System.out.println("Student with roll number 1: " + studentMap.get(1));
        System.println("Student with roll number 2: " + studentMap.get(2));
        System.println("Student with roll number 3: " + studentMap.get(3));

In this example, we create a new HashMap called studentMap that maps integers (roll numbers) to strings (student names). We add three entries using the put() method and retrieve their values using the get() method.

Advantages of HashMap:

  • Fast Retrieval: HashMap provides constant-time performance for retrieving values based on keys.
  • Flexible Key-Value Pairing: HashMap allows any object to be used as a key and any object to be used as a value.
  • No Duplicate Keys: HashMap does not allow duplicate keys. If you try to insert a value with an existing key, the new value will replace the old one.

Cautions When Using HashMap:

  • Inconsistent Iteration Order: The order in which elements are stored in a HashMap is not guaranteed. If you need a specific order, consider using other implementations like LinkedHashMap.
  • Mutability of Keys: Since the hash code of an object is used to determine its position in the array, it is crucial that the key objects are immutable.

    If a key’s hash code changes after being inserted into the HashMap, it may not be retrievable.

  • Performance Trade-offs: While HashMap provides fast retrieval, it consumes more memory compared to other data structures like arrays. It also has a higher time complexity for operations like resizing or rehashing.

With its efficient retrieval and flexibility, HashMap is a powerful data structure in Java that can be used in various scenarios. Understanding its inner workings and advantages will help you make informed decisions when choosing the right data structure for your applications.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy