Java / Java 21 Interview Questions
What are the contracts for equals(), hashCode(), and Comparable in Java?
These three methods have formal contracts that must be maintained for code to work correctly with collections, sorting, and data structures.
// equals() contract:
// 1. Reflexive: x.equals(x) == true
// 2. Symmetric: x.equals(y) == y.equals(x)
// 3. Transitive: x.equals(y) && y.equals(z) => x.equals(z)
// 4. Consistent: multiple calls return same result (no random state)
// 5. Null: x.equals(null) == false (never throws NPE)
// hashCode() contract:
// 1. Consistent: same object => same hashCode across calls
// 2. Equality: x.equals(y) MUST imply x.hashCode() == y.hashCode()
// 3. Collision: x.hashCode() == y.hashCode() does NOT imply x.equals(y)
// Records auto-generate correct equals() and hashCode()
record Point(int x, int y) {} // perfect equals and hashCode built-in
// Manual implementation (old style)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
// Comparable — natural ordering for TreeSet, TreeMap, Collections.sort
record Employee(String name, int salary) implements Comparable {
@Override
public int compareTo(Employee other) {
return Integer.compare(this.salary, other.salary); // ascending salary
}
}
// Comparator — external ordering (does not require modifying the class)
Comparator byNameThenSalary =
Comparator.comparing(Employee::name)
.thenComparingInt(Employee::salary); The most common bug: implementing equals() without updating hashCode(). Two objects that are equal will then have different hash codes, causing them to land in different hash buckets — a HashMap will store both, and HashSet will contain both, breaking uniqueness silently.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
