DEV Community

Cover image for ๐Ÿ” Understanding Hashing in Java: Exploring HashMap, HashSet, and hashCode() ๐Ÿš€
Melody Mbewe
Melody Mbewe

Posted on

7 1 1 1 2

๐Ÿ” Understanding Hashing in Java: Exploring HashMap, HashSet, and hashCode() ๐Ÿš€

Hashing in Java is an advanced concept that can enable one to store and retrieve data in the most effective manner. It does not matter whether one is experienced or fresher because knowing how hashing works helps take your programming skills to the next level, thus enabling your code to run way faster. In this article, we will break down everything about hashing with the three pillars: HashMap, HashSet, and the hashCode() method; simple code examples are included to get you up and running!

๐Ÿ“Œ What is Hashing?
Hashing, in simple terms, is a procedure of converting data into fixed-size numeric values that is popularly known as the hash code. The hash code is unique to the data and allows hash-based data structures to find the data fast. The aim of hashing is to have effective searches, inserts, and deletions.

Why is it Important?

  1. โšกSpeed: Hashing can provide data retrieval virtually in the snap of your fingers.
  2. ๐Ÿšซ Remove Duplicates: Hashing enables the addition of unique entries in data structures such as HashSet.

Now, letโ€™s jump into how Java uses hashing through HashMap, HashSet, and the hashCode() method! ๐Ÿ’ก

๐Ÿ”‘ 1. HashMap in Java ๐Ÿ—‚๏ธ
Image description
A HashMap stores data in key-value pairs, using hashing to quickly find the value associated with a particular key. Each key is converted into a hash code, which determines where the key-value pair will be stored.

Why Use HashMap?

  • Fast lookups โ€“ You can find or update values by key in constant time.

  • Flexibility โ€“ It allows null values and duplicate values but enforces unique keys.

HashMap Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<Integer, String> userMap = new HashMap<>();

        userMap.put(101, "Alice");
        userMap.put(102, "Bob");
        userMap.put(103, "Charlie");

        System.out.println("User with ID 101: " + userMap.get(101));

        userMap.remove(102);
        System.out.println("After removing ID 102: " + userMap);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we store usersโ€™ IDs as keys and their names as values. The HashMap uses the hash code of the key to locate the value quickly, making retrieval fast. ๐Ÿ”ฅ

๐ŸŒŸ 2. HashSet in Java ๐Ÿ”
Image description
A HashSet is used to store unique elements. It relies on the hashCode() method to ensure no two elements are identical. If you need a collection that guarantees no duplicates, HashSet is your go-to data structure!

Why Use HashSet?

  • Prevents duplicates โ€“ It automatically filters out duplicate entries.

  • Quick operations โ€“ Fast insertions, deletions, and lookups using hashing.

HashSet Example:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> userSet = new HashSet<>();

        userSet.add("Alice");
        userSet.add("Bob");
        userSet.add("Charlie");
        userSet.add("Alice"); 
        System.out.println("Is Bob in the set? " + userSet.contains("Bob"));

        userSet.remove("Charlie");

        System.out.println("Users in the set: " + userSet);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, "Alice" is added twice, but HashSet only stores it once, ensuring there are no duplicates. Magic of hashing! โœจ

๐Ÿ”ง 3. The hashCode() Method
Every object in Java has a hashCode() method inherited from the Object class. The hashCode() method generates a numeric hash code that uniquely represents the objectโ€™s data. But if you're working with custom objects in collections like HashMap or HashSet, it's essential to override hashCode() and equals() methods.

Why Override hashCode()?

  • To ensure custom objects can be properly hashed and compared.

  • To prevent issues with storing or looking up objects in hash-based structures.

Example: Custom Object with hashCode() and equals():

import java.util.Objects;

class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        User user = (User) obj;
        return id == user.id && name.equals(user.name);
    }

    @Override
    public String toString() {
        return name + " (ID: " + id + ")";
    }
}

public class CustomObjectExample {
    public static void main(String[] args) {
        HashSet<User> users = new HashSet<>();

        users.add(new User(101, "Alice"));
        users.add(new User(102, "Bob"));
        users.add(new User(101, "Alice")); 

        System.out.println("Users in the set: " + users);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we ensure that two User objects with the same ID and name are treated as equal, so the HashSet can avoid adding duplicates.

๐Ÿค How hashCode() and equals() Work Together ๐Ÿค
When an object is added to a HashMap or HashSet, Java first checks the hashCode() to determine the object's location. Then, the equals() method ensures that objects are compared properly for equality.

Best Practices:
Always override hashCode() and equals() together. If equals() indicates that two objects are equal, they must have the same hashCode().

๐Ÿ’ก๐Ÿ’ก Tips for All Skill Levels ๐Ÿง ๐Ÿง 

  • Beginners: Begin by grasping how HashMap and HashSet use hash codes for data storage. Focus on practical application rather than intricate details.

  • Intermediate Developers: Override hashCode() and equals() in your classes to observe their impact on hash-based collections.

  • Advanced Developers: Explore hash collisions and performance optimization in large-scale applications where hash efficiency is key.

๐Ÿ“ฃ Join the Conversation!
What are some of the challenges you've faced with hashing in Java? ๐Ÿค” Letโ€™s discuss them! Have you ever run into hash collisions, or had to override hashCode() and equals()? Share your thoughts and experiences in the comments below! ๐Ÿ’ฌ๐Ÿ‘‡

By mastering hashing in Java, you unlock the power of high-performance data structures! ๐Ÿ’ชโœจ

Now it's your turn to try out hashing in your code! ๐Ÿ–ฅ๏ธ๐Ÿ‘จโ€๐Ÿ’ป Happy coding!

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (2)

Collapse
 
trplx_gaming profile image
Gabriel Ibe โ€ข

This is another article I've read by you and you never seem to disappoint ๐Ÿ‘Œ๐Ÿผ

Nice article, these are making me learn Java quicker๐Ÿ˜Š

Collapse
 
devnenyasha profile image
Melody Mbewe โ€ข

Thank you so much, Gabriel! Iโ€™m so glad you found my posts insightful! Happy coding! ๐Ÿ˜Š

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up