# == vs equals() and the hashCode Contract

> What is the difference between == and equals()? Why must you override hashCode() whenever you override equals()?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-equals-hashcode-contract
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What is the difference between == and equals()? Why must you override hashCode() whenever you override equals()?

## Answer

Let me tell you why this question keeps surviving in interviews for a decade: bugs from breaking this contract are silent. Your code compiles, your tests on small data pass, and then a HashMap lookup randomly returns null in production. Interviewers want to see that you understand why.

First the simple part. The operator == compares what is stored in the variable. For primitives, that is the actual value, so 5 == 5 is true. For objects, the variable stores a reference, so == asks whether two references point to the exact same object in memory. That is identity.

The equals method, defined in Object, is meant to check logical equality. But the default implementation in Object is just this == obj, so unless a class overrides it, equals behaves the same as ==. String, Integer, List, LocalDate and most library classes override equals to compare content. Your own classes do not, unless you write it.

Now the contract. When you override equals, it must be reflexive (x equals x), symmetric (if x equals y then y equals x), transitive, consistent (same result on repeated calls if nothing changed) and return false for null. Symmetry is where inheritance bugs creep in, for example when a subclass compares with instanceof against the parent in one direction only.

The hashCode contract says: if two objects are equal according to equals, they must return the same hashCode. The reverse is not required; two unequal objects may share a hash code, that is just a collision and costs performance. Also, hashCode must return the same value across calls during one execution as long as the fields used in equals are unchanged.

Why does this matter? Hash-based collections such as HashMap, HashSet and Hashtable use hashCode to pick a bucket, and then use equals to find the exact key within the bucket. Imagine two Employee objects with the same id that are equal by your equals. If you did not override hashCode, each object inherits the identity-based hash from Object, so they land in different buckets. The map then never even calls equals, and get returns null for a key that is logically present. A HashSet would happily store duplicates.

Think of it as a library. The hash code is the shelf number, and equals is checking the exact book on that shelf. If two identical copies are sent to different shelves, you will never realize they are duplicates.

Best practice: use the same fields in both methods, and write them with Objects.equals and Objects.hash, or let your IDE or a record generate them. Records automatically generate correct equals and hashCode from all components.

Another important trap: do not use mutable fields in hashCode for objects used as map keys. If a key changes after insertion, its hash changes and the entry becomes unreachable, a subtle memory leak.

Finally, remember that Strings are special because == may accidentally work due to the pool, but you should never rely on that. Always use equals for content, and use Objects.equals(a, b) when either side may be null to avoid NullPointerException.

## Code examples

### Broken vs correct key class in a HashMap

```
import java.util.*;

public class ContractDemo {
    static class BadKey {
        final int id;
        BadKey(int id) { this.id = id; }
        @Override public boolean equals(Object o) {
            return o instanceof BadKey b && b.id == id;
        }
    }

    static class GoodKey {
        final int id;
        GoodKey(int id) { this.id = id; }
        @Override public boolean equals(Object o) {
            return o instanceof GoodKey g && g.id == id;
        }
        @Override public int hashCode() { return Objects.hash(id); }
    }

    public static void main(String[] args) {
        Map<BadKey, String> bad = new HashMap<>();
        bad.put(new BadKey(1), "A");
        System.out.println(bad.get(new BadKey(1)));

        Map<GoodKey, String> good = new HashMap<>();
        good.put(new GoodKey(1), "A");
        System.out.println(good.get(new GoodKey(1)));
    }
}
```

BadKey inherits an identity-based hashCode, so two equal keys go to different buckets and get returns null (in practice always). GoodKey follows the contract and the lookup succeeds.

## Key points

- == compares references for objects; equals compares logical content once overridden.
- Equal objects must have equal hash codes; equal hash codes do not imply equal objects.
- HashMap uses hashCode to choose the bucket and equals to find the key inside it.
- Use the same fields in equals and hashCode, and avoid mutable fields for keys.
- Records generate correct equals and hashCode automatically.

## Common follow-up questions

- What happens if hashCode always returns 1?
- Can two unequal objects have the same hashCode?
- How does equals behave with inheritance and getClass vs instanceof?
- What is the default hashCode of Object?

## Interview tips

- Say the contract in one sentence: equal objects must produce equal hash codes. Then give the HashMap example.
- Mention Objects.equals and Objects.hash to show you write safe, null-tolerant code.

## Concepts covered

equals, hashCode, Object Identity, HashMap, Contract

Previous: [String vs StringBuilder vs StringBuffer](https://www.internhack.in/learn/interview/java-interview/java-string-stringbuilder-stringbuffer) · Next: [final vs finally vs finalize](https://www.internhack.in/learn/interview/java-interview/java-final-finally-finalize) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [The static Keyword: Variables, Methods, Blocks and Nested Classes](https://www.internhack.in/learn/interview/java-interview/java-static-keyword)
- [Wrapper Classes, Autoboxing and the Integer Cache](https://www.internhack.in/learn/interview/java-interview/java-wrapper-autoboxing-integer-cache)
- [Checked vs Unchecked Exceptions](https://www.internhack.in/learn/interview/java-interview/java-checked-vs-unchecked-exceptions)
- [try-with-resources and AutoCloseable](https://www.internhack.in/learn/interview/java-interview/java-try-with-resources)
- [The Java Collections Framework Hierarchy](https://www.internhack.in/learn/interview/java-interview/java-collections-hierarchy)
- [ArrayList vs LinkedList](https://www.internhack.in/learn/interview/java-interview/java-arraylist-vs-linkedlist)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
