DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Effective Java Collection Framework: Best Practices and Tips
  • Generics in Java and Their Implementation
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems

Trending

  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • How to Convert Between PDF and TIFF in Java
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  1. DZone
  2. Data Engineering
  3. Data
  4. Java HashMap Implementation in a Nutshell

Java HashMap Implementation in a Nutshell

Want to learn more about custom HashMap implementation in Java? Check out this tutorial on how we can implement this data structure using arrays.

By 
Yogen Rai user avatar
Yogen Rai
·
Oct. 08, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
202.2K Views

Join the DZone community and get the full member experience.

Join For Free

A HashMap (or hash table) is a data structure that maps keys to values for highly efficient lookup. There are a number of ways to implement this data structure. This post is about the simple implementation of HashMaps in Java using an array of a linked list.

So, let's first define a class representing a node of a linked list as:

class Entry<K, V> {
    final K key;
    V value;
    Entry<K, V> next;

    public Entry(K key, V value, Entry<K, V> next) {
        this.key = key;
        this.value = value;
        this.next = next;
    }

    // getters, equals, hashCode and toString
}


Inserting Element

To insert an element, a key and value, we do the following:

  1. First, compute the key's hash code, which will usually be an int. The two different objects could have the same hash code, as there may be an infinite number of elements and a finite number of ints.
  2. Then, calculate the index in the array using hash code using modulo as  hashCode (key) % array_length. Here, two different hash codes could map to the same index.
  3. Get the linked list at this index calculated above. Store the element in this index. The use of a linked list is important because of collisions: you could have two different keys with the same hash code or two different hash codes that map to the same index.

The picture below shows explains this.

hashmap-example

This can be implemented as:

public class MyMap<K, V> {
    private Entry<K, V>[] buckets;
    private static final int INITIAL_CAPACITY = 1 << 4; // 16

    private int size = 0;

    public MyMap() {
        this(INITIAL_CAPACITY);
    }

    public MyMap(int capacity) {
        this.buckets = new Entry[capacity];
    }

    public void put(K key, V value) {
        Entry<K, V> entry = new Entry<>(key, value, null);

        int bucket = getHash(key) % getBucketSize();

        Entry<K, V> existing = buckets[bucket];
        if (existing == null) {
            buckets[bucket] = entry;
            size++;
        } else {
            // compare the keys see if key already exists
            while (existing.next != null) {
                if (existing.key.equals(key)) {
                    existing.value = value;
                    return;
                }
                existing = existing.next;
            }

            if (existing.key.equals(key)) {
                existing.value = value;
            } else {
                existing.next = entry;
                size++;
            }
        }
    } 
    // . . .
}


Retrieving Element

The retrieval of the element from HashMap can be done with the following steps:

  1. Compute the hash code from the key, and then compute the index from the hash code with module operation.
  2. Then, get the linked list at index computed above and search through the linked list for the value with this value.

The implementation can be as simple as the following:

public V get(K key) {
    Entry<K, V> bucket = buckets[getHash(key) % getBucketSize()];

    while (bucket != null) {
        if (bucket.key.equals(key)) {
            return bucket.value;
        }
        bucket = bucket.next;
    }
    return null;
}


Testing

The custom HashMap implemented above can be tested easily as:

@Test
public void testMyMap() {
    MyMap<String, String> myMap = new MyMap<>();
    myMap.put("USA", "Washington DC");
    myMap.put("Nepal", "Kathmandu");
    myMap.put("India", "New Delhi");
    myMap.put("Australia", "Sydney");

    assertNotNull(myMap);
    assertEquals(4, myMap.size());
    assertEquals("Kathmandu", myMap.get("Nepal"));
    assertEquals("Sydney", myMap.get("Australia"));
}


Time Complexity

Since different keys can be mapped to the same index, there is a chance of collision. If the number of collisions is very high, the worst case runtime is O(n), where n is the number of keys.
However, we generally assume a good implementation that keeps collisions to a minimum, in which case the lookup time is O(1).

Conclusion

This post illustrated how HashMap (or HashTable) can be implemented with an array-based linked list. You can take a look more examples on Cracking the Coding Interview by Gayle Laakmann McDowell.

The source code for all example presented above is available on GitHub.



If you enjoyed this article and want to learn more about Java Collections, check out this collection of tutorials and articles on all things Java Collections.

Data structure Implementation Java (programming language)

Published at DZone with permission of Yogen Rai, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Effective Java Collection Framework: Best Practices and Tips
  • Generics in Java and Their Implementation
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!