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 protect your PDF file with password online ?

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

Read More >

Free tool to convert Excel (.xls/.xlsx) file to PDF online.

When you want to share your spreadsheet data with others who may not have Excel or who need a format...

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 >

Free tool to convert text to pdf online with no restriction

A free tool to convert one or multiple text files to PDF online, at no-cost, no-registration, and no...

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 >

How to convert image to pdf online using converteasly?

A free tool to convert one or multiple images to PDF online, at no-cost, no-registration, and no-ins...

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 >

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 >

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 >

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

Simple steps to delete pages from your PDF file online using converteasly

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

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 >

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 >

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 >

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 >

Simple steps to split single PDF into multiple PDF online using converteasly

you can extract a single chapter from a large book or isolate specific sections for reference or dis...

Read More >

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

By converting WebP images to JPEG or PNG, you ensure compatibility with a broader range of devices, ...

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 >

Effortless JSON Viewing & Editing with Converteasly – Simplify Your Workflow

Are you looking for a tool to help you work with JSON data?, you might be tired of dealing with the ...

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 >

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 PDF to Image online using converteasly?

Simple steps to convert PDF to images online, at no-cost, no-registration, and no-installation neede...

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 >

How to compress or reduce image size online using converteasly ?

Compressing images is crucial for optimizing website performance. Large image file sizes can signifi...

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 >

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 Convert HEIC to JPEG Online Using Converteasly

Easily convert HEIC images from your iPhone or iPad to universally compatible JPEG format without lo...

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 change width and height of image online free ?

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

Read More >

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