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

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 >

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

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 >

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

Legal professionals often convert legal documents, agreements, and contracts from RTF to PDF to maintain document integrity and

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 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 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 document. Text search functionality allows you to quickly locate relevant information

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 >

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

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

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

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

Learn the difference between equals() and hashCode() in Java, their relationship, and why they matter when working with collections like HashMap and HashSet.

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 >

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 >

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

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 >

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 >

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

Read More >

How to convert ODF Formula (.odf) file to PDF online using converteasly ?

Educators can convert course materials, lecture notes, and educational resources from ODF to PDF format for distribution to students

Read More >

Understanding the Concept of Inheritance in Java with application

Let's dive into the concept of inheritance more deeply with a lots of examples

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 >

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 >

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 Escape JSON Using Converteasly

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

Read More >

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