THE GENERAL BLOG

Understanding equals() and hashCode() in Java with Examples

Posted on October 18, 2025

When working with Java objects, you’ll often need to compare them — not just by memory reference, but by their actual content.
That’s where equals() and hashCode() come in. These two methods are crucial for object comparison, especially when using Java collections like HashMap, HashSet, or Hashtable.

🧩 What Are equals() and hashCode()?

Both equals() and hashCode() are methods inherited from Java’s Object class — the root of all Java classes.

public boolean equals(Object o);
public int hashCode();

equals()

The equals() method compares two objects logically — meaning, it checks whether the values inside the objects are the same, not just whether they occupy the same memory address.

Example 1: String Comparison

String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // false

Explanation: equals() checks the value, while == checks the memory reference. Since String overrides equals() internally to compare character sequences, s1.equals(s2) returns true.

Here’s how the String class overrides equals():

public boolean equals(Object anObject) {
    if (this == anObject) return true;
    if (anObject instanceof String) {
        String aString = (String) anObject;
        return coder() == aString.coder()
            ? StringLatin1.equals(value, aString.value)
            : StringUTF16.equals(value, aString.value);
    }
    return false;
}

Example 2: Custom Class Without Overriding equals()

class Person {
    private String name;
    private int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Person p1 = new Person("Suresh", 25);
Person p2 = new Person("Suresh", 25);

System.out.println(p1.equals(p2)); // false
System.out.println(p1 == p2); // false

Explanation: Since Person doesn’t override equals(), it uses the default version from the Object class, which compares memory references — not values. Hence, both comparisons return false.

Let’s fix that:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Person) {
        Person p = (Person) obj;
        return this.name.equals(p.name) && this.age == p.age;
    }
    return false;
}

Now, comparing p1.equals(p2) will return true.

hashCode()

The hashCode() method returns an integer hash value representing the object. It’s used mainly in hash-based collections, such as:

  • HashMap
  • HashSet
  • Hashtable

The hash code determines where an object is stored inside these data structures.

🔗 The Contract Between equals() and hashCode()

There’s a fundamental rule in Java:

If two objects are equal according to equals(), they must have the same hashCode().

In other words:

if (a.equals(b)) {
    assert a.hashCode() == b.hashCode(); // must be true
}

However, the reverse is not always true — two unequal objects can have the same hash code (known as a hash collision).

💡 Why It Matters (Real-World Use Cases)

✅ Use Case: Storing Objects in Hash Collections

When you add an object to a HashSet or use it as a key in a HashMap, Java does the following:

  1. Calls hashCode() → to find the bucket where the object should go.
  2. Calls equals() → to check if an identical object already exists in that bucket.

If you don’t override these methods correctly, duplicate or missing data issues can occur.

Example:

class Person {
    String name;
    Person(String name) { this.name = name; }
}

Person p1 = new Person("Alice");
Person p2 = new Person("Alice");

HashSet<Person> set = new HashSet<>();
set.add(p1);
System.out.println(set.contains(p2)); // false! equals/hashCode not overridden

🛠️ Correct Way to Override equals() and hashCode()

class Person {
    String name;
    Person(String name) { this.name = name; }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Person)) return false;
        Person other = (Person) obj;
        return name.equals(other.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

Now this will work as expected:

HashSet<Person> set = new HashSet<>();
set.add(p1);
System.out.println(set.contains(p2)); // true
System.out.println(p1.equals(p2)); // true

🧠 Summary Table: equals() vs hashCode()

Method Purpose Common Use Case
equals() Compares two objects logically Used for content comparison
hashCode() Generates a unique integer value Used in HashMap, HashSet, etc.

🚀 Key Takeaways

  • Always override both equals() and hashCode() when creating custom classes.
  • Use consistent logic in both methods.
  • Remember: Equal objects must have the same hash code.
  • Improper overriding can lead to bugs in collections and unexpected behavior.

📘 Further Reading

In short: If your class objects are meant to be compared or stored in sets/maps — never forget to properly override equals() and hashCode(). It’s a small step that prevents big headaches later.



The Most Popular Blog

The best tips and tricks on managing digital documents

How to convert jpg or jpeg to png online using converteasly ?

Converting JPG to PNG can be useful when you want to compress an image while maintaining its quality...

Read More >

How to Convert AVIF Images to PDF Online Free Using Converteasly

Easily convert AVIF images into universally compatible PDF documents for sharing, printing, and arch...

Read More >

Simple steps to decode Base64 to Text online using converteasly

Some APIs return data in Base64 encoded format, especially when dealing with binary data or non-text...

Read More >

Understanding equals() and hashCode() in Java with Examples

Learn the difference between equals() and hashCode() in Java, their relationship, and why they matte...

Read More >

How HashSet Works Internally in Java — Step-by-Step Explanation with Example

Understanding HashSet in Java: Internal Working, HashMap Relation, and Efficiency Explained

Read More >

Understanding Git and GitHub: A Beginner's Guide with Simple Examples

If you're diving into the world of coding, you've probably heard about Git and GitHub. They're like ...

Read More >

How to Create and Download Your Digital Signature Securely Online

Draw your signature safely online with Converteasly — fast, free, and privacy-first.

Read More >

How to Escape JSON Using Converteasly

Dealing with JSON data often requires ensuring that the text is properly escaped to avoid errors dur...

Read More >

How to Unescape JSON Using Converteasly

Are you dealing with escaped JSON that needs to be converted back to its original form?

Read More >

Simple and Free tool to convert PPT file to PDF online with no restrictions.

When sharing slides with others who may not have PowerPoint or when you want to ensure that the cont...

Read More >

Convert AVIF images to JPEG online using Converteasly

Convert AVIF images to JPEG quickly and easily without losing quality, directly from your browser.

Read More >

How to convert Rich Text Format (.rtf) file to Epub online free using converteasly ?

Educational institutions and educators can convert RTF-based textbooks, study guides, and educationa...

Read More >

How to convert PDF to Text free online with no restriction ?

Converting PDF to text makes it easier to search for specific words, phrases, or keywords within the...

Read More >

Unlocking Creativity: Understanding Generative AI and Its Everyday Applications.

Welcome to the world of Generative AI, where algorithms transform data into something entirely new, ...

Read More >

How to convert Docx file to Epub online free using converteasly ?

Teachers, educators, and instructional designers can convert lesson plans, textbooks, educational gu...

Read More >

Simple and Free tool to merge multiple Docx file into single Docx online.

When preparing presentations, different team members might be responsible for various sections. A me...

Read More >

How to protect your PDF file with password online ?

When sharing sensitive or confidential documents, protecting the PDF ensures that only intended reci...

Read More >

How to Convert JPG/PNG to WebP Using Converteasly.com

Optimizing images for the web is essential for faster loading times and better user experience. Conv...

Read More >

Effortlessly Compare JSON Objects & Arrays with Converteasly

Are you getting frusted to compare two json data using online tools ? here is the solution for you.

Read More >

How to Convert HEIF to JPEG Online Using Converteasly

Easily convert HEIF images from iPhone or iPad into JPEG for universal compatibility and sharing.

Read More >

How to change width and height of image online free ?

Resizing images is crucial for optimizing website performance and improving user experience.

Read More >

Understanding the concept of Encapsulation and Polymorphism in java

Encapsulation is a fundamental principle in object-oriented programming (OOP) where the internal sta...

Read More >

How to rotate image left and right online using converteasly ?

Images captured with digital cameras or smartphones may sometimes have incorrect orientations due to...

Read More >

Unlocking the Power of Java Multithreading

Multithreading is a programming technique that enables a program to execute multiple threads or flow...

Read More >

Convert HEIC to PDF Online Easily with Converteasly

Easily convert HEIC images from iPhones or iPads into universally compatible PDF documents without l...

Read More >

How to Remove Background of Image using converteasly

In today digital world, having images with transparent backgrounds is often a necessity for designer...

Read More >

How to convert docx file to pdf online free ?

Presentations created in DOCX format might need to be shared with clients or partners. Converting th...

Read More >

How to Merge one or multiple PDFs into single PDf online ?

Merge PDF functionality is helpful for compiling e-books or digital publications. Authors or publish...

Read More >

Exploring JDK 17 Features: A Comprehensive Guide

Java Development Kit (JDK) 17, released in September 2021, is the Long-Term Support (LTS) version of...

Read More >

How to unlock password protected PDF online using converteasly ?

Unlocking password-protected PDFs or removing restrictions can streamline document workflows, especi...

Read More >

© 2025 converteasly.com - Made with love 💕 for the people of the internet.