Sub topic 14
Overriding equals, hashCode, and toString
Every class in Java inherits from one class at the very top: Object. Object is the root class of all Java classes. Even when you write class Point with no extends, Java quietly treats it as class Point extends Object.
Object gives every class a few methods for free. Three of them matter a lot in daily work:
equals(Object o)is a method that answers "do these two objects mean the same thing?"hashCode()is a method that returns anintused by hash-based collections such asHashSetandHashMap.toString()is a method that returns a text version of the object. Java calls it when you print an object or join it to a string.
The versions in Object are very basic. In this chapter you will override all three. You will also see why they must agree with each other, and how a small mistake can break your program without any error message.
What the Default Versions Do
The default equals checks identity. Identity means "is this the exact same object in memory?" Two separate objects with the same data are not equal by default.
The default hashCode gives a number tied to that one object. It is not based on the object's data.
The default toString prints the class name, an @ sign, and the hash code in hexadecimal. Hexadecimal is base 16, so it looks like Point@1b6d3586. Users get nothing useful from that.
| Method | Default behavior from `Object` | What you usually want |
|---|---|---|
| `equals` | True only for the same object | True when the important fields match |
| `hashCode` | Based on the object's identity | Based on the same fields as `equals` |
| `toString` | `ClassName@hexcode` | Readable text showing the fields |
A Broken Example First
Here is a class that tries to define equality but gets the parameter type wrong. It takes a BrokenPoint instead of an Object. Read it, then run it.
import java.util.ArrayList;
import java.util.List;
class BrokenPoint {
final int x;
final int y;
BrokenPoint(int x, int y) {
this.x = x;
this.y = y;
}
// Wrong: this OVERLOADS equals instead of overriding it.
public boolean equals(BrokenPoint other) {
return x == other.x && y == other.y;
}
}
public class Main {
public static void main(String[] args) {
BrokenPoint a = new BrokenPoint(1, 2);
BrokenPoint b = new BrokenPoint(1, 2);
System.out.println(a.equals(b)); // true (calls the overload)
Object o = b;
System.out.println(a.equals(o)); // false (calls Object.equals)
List<BrokenPoint> list = new ArrayList<>();
list.add(a);
System.out.println(list.contains(b)); // false
System.out.println(a); // something like BrokenPoint@1b6d3586
}
}The output shows the problem. When the argument's declared type is BrokenPoint, the compiler picks the new method. When the declared type is Object, the compiler picks the original equals(Object) from Object, which only checks identity.
Library code such as ArrayList.contains always calls equals(Object). So the list says it does not contain b, even though b has the same data as a.
You saw this in the chapter on overloading versus overriding. The compiler chooses an overload by declared types. This is the most common real-world example of that rule.
The equals Contract
A contract is a set of promises a method must keep so other code can trust it. Collections, sorting tools, and other libraries depend on equals keeping these promises.
| Rule | Plain meaning |
|---|---|
| Reflexive | `x.equals(x)` is always true. |
| Symmetric | If `x.equals(y)` is true, then `y.equals(x)` is true. |
| Transitive | If `x` equals `y` and `y` equals `z`, then `x` equals `z`. |
| Consistent | Asking again gives the same answer if nothing changed. |
| Non-null | `x.equals(null)` is always false and never crashes. |
Doing It Right: A Complete Point Class
Here is a correct version. Save it as Main.java, compile with javac Main.java, and run with java Main.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // same object
if (!(o instanceof Point)) return false; // null or another type
Point other = (Point) o; // safe cast
return x == other.x && y == other.y; // compare fields
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
Point c = new Point(3, 4);
System.out.println(a.equals(b)); // true
System.out.println(a.equals(c)); // false
System.out.println(a.equals(null)); // false
Object o = b;
System.out.println(a.equals(o)); // true, now overridden
Set<Point> set = new HashSet<>();
set.add(a);
System.out.println(set.contains(b)); // true
System.out.println(a); // Point(1, 2)
System.out.println("Start at " + c); // Start at Point(3, 4)
}
}Look at the four steps inside equals:
- If both references point to the same object, return
trueright away. This is fast and covers the reflexive rule. o instanceof Pointis false whenoisnull, so this one check handles bothnulland wrong types. That covers the non-null rule.- After the check, the cast to
Pointis safe. You learned about this in the casting chapter. You could also writeif (!(o instanceof Point other)) return false;with pattern matching on Java 16 or later. - Compare the fields that define what the object means.
The class is marked final, so no one can subclass it. This matters for symmetry. If a subclass ColorPoint added a color and its own equals, a Point might say it equals a ColorPoint while the ColorPoint says the opposite. Making the class final avoids that problem.
Why hashCode Must Match equals
A HashSet does not compare your object with every item it holds. That would be slow. It uses the hash code to jump to a small group of items called a bucket. Then it calls equals only on the items in that bucket.
If you override equals but not hashCode, two equal points will almost always get different hash codes from Object. The set looks in the wrong bucket and never calls your equals. So contains returns false, and you get no error message to tell you why.
The rule is short:
- If
a.equals(b)is true, thena.hashCode()must equalb.hashCode(). - Two unequal objects may share a hash code. That is allowed, just a little slower.
Objects.hash(x, y) builds a hash code from the same fields you compared in equals. Use exactly those fields, no more and no fewer.
toString and Polymorphism
System.out.println(a) does not know about Point. It receives an Object and calls toString() on it. Dynamic dispatch picks your overridden version at runtime, so you see Point(1, 2). String joining with + works the same way.
This is polymorphism at work. Library code written years before your class existed still runs your code, because it calls the methods through an Object reference.
Good toString output is short, shows the important fields, and helps you when you debug. It is mainly for developers to read. Do not write code that parses it.
Common Mistakes Checklist
- Writing
equals(Point p)instead ofequals(Object o). This overloads the method instead of overriding it. - Overriding
equalswithout overridinghashCode. - Using different fields in
equalsandhashCode. - Crashing on
nullby callingo.getClass()or reading a field before checking for null. - Comparing
Stringfields with==instead of.equals. For object fields, useObjects.equals(a, b), which also handlesnull. - Making
toStringtoo long or including secret data such as passwords.
Exercise
A class overrides equals(Object) correctly but does not override hashCode. You add one object to a HashSet, then call contains with a second object that has the same field values. What will most likely happen, and why?
Show answer
contains will most likely return false. HashSet calls hashCode first to choose a bucket. Without an override, each object gets an identity-based hash code from Object, so the two objects usually land in different buckets and equals is never called.
Exercise
Why does a.equals(o) return false in the BrokenPoint example when o is declared as Object, even though it refers to a BrokenPoint with the same x and y?
Show answer
equals(BrokenPoint) is an overload, not an override. The compiler picks an overload from the declared argument type. Since o is declared as Object, it picks Object.equals(Object), which only checks whether both references point to the same object.
Exercise
Add a String field called label to Point. Write the field comparison line for equals and the body of hashCode so that both use x, y, and label, and a null label does not crash.
Show answer
In equals, use: return x == other.x && y == other.y && Objects.equals(label, other.label); In hashCode, use: return Objects.hash(x, y, label); Objects.equals and Objects.hash both handle null safely.