← Back to Questions
Java

Difference between equals() and hashCode()?

Learn Difference between equals() and hashCode()? with simple explanations, real-time examples, interview tips and practical use cases.

Difference Between equals() and hashCode() in Java

In Java, equals() and hashCode() are methods from the Object class used for object comparison and hashing operations.

In simple words:

equals() checks logical equality between objects, while hashCode() returns an integer hash value used for fast searching and storage in hash-based collections.


Why Understanding equals() and hashCode() is Important?

These methods are extremely important in:

  • HashMap
  • HashSet
  • Spring Boot applications
  • Hibernate entities
  • Caching systems
  • Distributed systems
  • Microservices
  • Banking applications

equals() and hashCode() Overview Diagram


Object

      |
      +-------> hashCode()

      |
      +-------> equals()


What is equals()?

equals() method checks whether two objects are logically equal.


equals() Example

String s1 = "Java";

String s2 = "Java";

System.out.println(
    s1.equals(s2)
);

Output

true

Why?

Because both Strings contain same content.


equals() Flow


Two Objects Passed

      |
      v

Content Compared

      |
      v

Logical Equality Returned


What is hashCode()?

hashCode() method returns an integer hash value representing object data.


Example

String s = "Java";

System.out.println(
    s.hashCode()
);

Purpose of hashCode()

hashCode() improves searching performance in hash-based collections.


hashCode() Flow


Object Data

      |
      v

Hash Algorithm Applied

      |
      v

Integer Hash Generated


Main Difference Table

Feature equals() hashCode()
Purpose Logical Equality Hash Generation
Return Type boolean int
Used In Object Comparison Hash-Based Collections
Defined In Object Class Object Class
Can Override? Yes Yes

Default Implementation of equals()

public boolean equals(
    Object obj
) {

    return (this == obj);

}

Meaning

Default equals() compares object references.


Default hashCode() Behavior

Default hashCode() generates value based on memory address.


Important Contract Between equals() and hashCode()

Java defines strict rules:


Rule 1

If two objects are equal using equals(), their hashCode() must also be equal.


Rule 2

If hashCodes are same, objects may or may not be equal.


Contract Diagram


equals() = true

      |
      v

hashCode() MUST be same


Why This Contract is Important?

Because HashMap and HashSet depend on both methods.


HashMap Internal Flow


Object Inserted

      |
      v

hashCode() Called

      |
      v

Bucket Located

      |
      v

equals() Checks Exact Match


Custom Class Example

class Employee {

    int id;

}

Without Overriding equals() and hashCode()

Employee e1 =
    new Employee();

Employee e2 =
    new Employee();

e1.id = 101;
e2.id = 101;

System.out.println(
    e1.equals(e2)
);

Output

false

Why?

Default equals() compares references.


Correct equals() Implementation

@Override
public boolean equals(
    Object obj
) {

    Employee e =
        (Employee)obj;

    return this.id == e.id;

}

Correct hashCode() Implementation

@Override
public int hashCode() {

    return id;

}

Now Comparison

System.out.println(
    e1.equals(e2)
);

Output

true

Object Comparison Flow


hashCode() Compared

      |
      v

Same Bucket Located

      |
      v

equals() Performs Exact Match

      |
      v

Objects Treated Equal


Problem If hashCode() is Not Overridden

Collections may behave incorrectly.


HashSet Example

HashSet set =
    new HashSet<>();

set.add(e1);
set.add(e2);

Problem

Duplicate objects may be stored.


Why?

Different hashCodes cause different buckets.


Incorrect Flow


Objects Logically Equal

      |
      v

Different hashCodes Generated

      |
      v

Different Buckets Used

      |
      v

Duplicates Stored


Correct HashSet Flow


hashCode() Same

      |
      v

Same Bucket Located

      |
      v

equals() Checks Equality

      |
      v

Duplicate Prevented


Why hashCode() Improves Performance?

Without hashCode(), collections would need full search every time.


Performance Flow


hashCode()

      |
      v

Direct Bucket Access

      |
      v

Fast Lookup


Real String Example

String s1 = "Java";

String s2 = "Java";

Results

s1.equals(s2)  -> true

s1.hashCode()
==
s2.hashCode()

Why?

Strings with same content generate same hashCode.


equals() and hashCode() in Banking Systems

Banking systems use these methods for:

  • Account comparison
  • Transaction deduplication
  • Caching
  • Fraud detection
  • Distributed transaction tracking

Banking Example

class Account {

    Long accountId;

}

Why Override?

Different objects representing same account should be treated equal.


Banking Flow


Account Objects Loaded

      |
      v

hashCode() Finds Bucket

      |
      v

equals() Validates Same Account


equals() and hashCode() in E-Commerce Systems

E-commerce applications use them for:

  • Cart item comparison
  • Order deduplication
  • Product caching
  • User session management

equals() and hashCode() in Spring Boot

Spring Boot applications use them heavily in:

  • JPA entities
  • Hibernate caching
  • Security contexts
  • REST DTO validation

Spring JPA Example

@Entity
class User {

    Long id;

}

Why Important?

Hibernate collections and caching rely on proper equality logic.


Hibernate Flow


Entity Loaded

      |
      v

hashCode() Locates Cache Entry

      |
      v

equals() Validates Entity Match


equals() and hashCode() in Microservices

Microservices architectures use them for:

  • DTO comparisons
  • Distributed caching
  • Kafka event deduplication
  • API response validation

Microservice Flow


Distributed Event Received

      |
      v

hashCode() Finds Cache Bucket

      |
      v

equals() Checks Duplicate Event


Difference Between ==, equals(), and hashCode()

Feature == equals() hashCode()
Purpose Reference Comparison Logical Equality Hash Generation
Return Type boolean boolean int
Used In Reference Check Content Comparison Hash Collections

Advantages of Proper equals() and hashCode()

  • Correct collection behavior
  • Better performance
  • Reliable caching
  • Accurate object comparison
  • Framework compatibility

Problems with Incorrect Implementation

  • Duplicate entries
  • HashMap failures
  • Cache inconsistencies
  • Collection bugs
  • Performance issues

Common Interview Mistake

Many developers override equals() but forget hashCode().

Actually:

  • Both methods must be overridden together.

Another Common Mistake

Many developers think same hashCode means objects are equal.

Actually:

  • Same hashCode does not guarantee equality.

Best Practices

  • Always override equals() and hashCode() together
  • Use immutable fields for hashCode calculation
  • Prefer Objects.hash() utility method
  • Keep equality logic consistent
  • Avoid mutable fields in hashCode()

Realtime Enterprise Example

Distributed Banking Cache


Transaction Object Created

      |
      v

hashCode() Finds Cache Bucket

      |
      v

equals() Checks Existing Transaction

      |
      v

Duplicate Transaction Prevented


Related Learning Topics


Professional Interview Answer

equals() and hashCode() are methods from the Object class used for logical object comparison and hashing operations in Java. The equals() method checks whether two objects are logically equal based on business data, while hashCode() generates an integer hash value used for efficient storage and searching in hash-based collections like HashMap and HashSet. Java defines an important contract stating that if two objects are equal according to equals(), they must return the same hashCode(). Enterprise applications, Spring Boot systems, banking platforms, Hibernate ORM frameworks, distributed caching systems, Kafka event processors, and cloud-native microservices heavily rely on properly implemented equals() and hashCode() methods for caching, entity comparison, duplicate prevention, distributed processing, collection management, and high-performance lookup operations. Improper implementation may lead to duplicate objects, cache inconsistency, and collection-related bugs.


Frequently Asked Questions

What does equals() do in Java?

equals() checks logical equality between objects.

What does hashCode() do?

hashCode() generates integer hash value for fast lookup.

Why should equals() and hashCode() be overridden together?

Because hash-based collections depend on both methods.

Can two unequal objects have same hashCode?

Yes, this is called hash collision.

Which collections use hashCode() heavily?

HashMap, HashSet, Hashtable, and ConcurrentHashMap.

Why this Java question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.