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 unlock password protected PDF online using converteasly ?

Unlocking password-protected PDFs or removing restrictions can streamline document workflows, especially in business or administrative settings.

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 publishers can combine individual chapters

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 >

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 >

Unlocking Creativity: Understanding Generative AI and Its Everyday Applications.

Welcome to the world of Generative AI, where algorithms transform data into something entirely new, giving machines the ability to create, imagine, and innovate.

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 publishers can combine individual chapters

Read More >

How to convert Pdf To Docx file online free using converteasly ?

If you have received a document in PDF format but need to continue working on it converting it to DOCX allows you to seamlessly resume

Read More >

Understanding the concept of Encapsulation and Polymorphism in java

Encapsulation is a fundamental principle in object-oriented programming (OOP) where the internal state of an object is hidden from outside access.

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. Converting JPG and PNG images to WebP format is an effective way to achieve this.

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 >

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

Converting PNG images to JPG format can significantly reduce the file size, making it more suitable for web publishing, email attachments, or

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

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

Read More >

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

Teachers, educators, and instructional designers can convert lesson plans, textbooks, educational guides, and study materials from DOCX to EPUB

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 content remains as intended

Read More >

How to Remove Background of Image using converteasly

In today digital world, having images with transparent backgrounds is often a necessity for designers, content creators, and anyone looking to create polished visuals.

Read More >

How to encode text into base64 format online using converteasly?

In some cases, when passing text data as a parameter in a URL, Base64 encoding can be used to ensure that

Read More >

How to protect your PDF file with password online ?

When sharing sensitive or confidential documents, protecting the PDF ensures that only intended recipients can access the content.

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 merge DOCX tool lets you bring together

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 that cannot be easily edited, converting to PDF

Read More >

Unlocking the Power of Java Multithreading

Multithreading is a programming technique that enables a program to execute multiple threads or flows of execution concurrently

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-textual content.

Read More >

Comprehensive Guide to Exception Handling in Java

Exception handling is a programming practice used to manage errors and exceptional conditions in a controlled manner.

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

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 the dynamic duo of version control, helping developers

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 educational resources into EPUB format

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 complexity of JSON files and the time it takes to manually parse and edit them.

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 significantly impact page load times, leading to slower website speeds

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 device positioning.

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

Read More >

Ā© 2025 converteasly.com - Made with šŸ’• for the people of the internet.

Consent PreferencesPrivacy PolicyDisclaimerT&C