DEV Community

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

Posted on

πŸ” 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!

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! 😊