Every Java class inherits three methods from Object that decide how its objects are compared, stored and printed: equals(), hashCode() and toString(). The versions you inherit compare memory addresses and print cryptic codes, which is rarely what you want. Getting them wrong causes some of Java’s most confusing bugs, such as a HashSet that keeps “duplicate” objects. This lesson shows the default behaviour, how to override all three correctly, and how records do it for you.
In this lesson you will learn
- The difference between
==andequals() - What the default methods from
Objectdo - Writing a correct
equals()method - The
equals/hashCodecontract and why hash collections need it - A readable
toString(), and letting records generate all three
You should know classes and objects and HashMap.
The Default Behaviour
import java.util.HashSet;
import java.util.Set;
public class Main {
// A class that does NOT override equals, hashCode or toString
static class PointA {
int x, y;
PointA(int x, int y) { this.x = x; this.y = y; }
}
public static void main(String[] args) {
PointA p1 = new PointA(2, 3);
PointA p2 = new PointA(2, 3);
PointA p3 = p1;
System.out.println("p1 == p2: " + (p1 == p2)); // different objects
System.out.println("p1 == p3: " + (p1 == p3)); // same object
System.out.println("p1.equals(p2): " + p1.equals(p2)); // default equals is ==
// default toString is ClassName@hexHashCode; the hex part changes from run to run
System.out.println("toString: " + p1.toString().replaceAll("@.*", "@...."));
Set<PointA> set = new HashSet<>();
set.add(p1);
set.add(p2);
System.out.println("set size: " + set.size() + ", contains (2,3)? "
+ set.contains(new PointA(2, 3)));
String s1 = new String("dhaka"), s2 = new String("dhaka");
System.out.println("Strings: == " + (s1 == s2) + ", equals " + s1.equals(s2));
}
}
Output
p1 == p2: false
p1 == p3: true
p1.equals(p2): false
toString: Main$PointA@....
set size: 2, contains (2,3)? false
Strings: == false, equals true
==on objects asks “are these the same object in memory?”.p1andp2hold equal coordinates but are two separate objects, sop1 == p2is false.p3is just another name forp1.- The
equals()inherited fromObjectdoes exactly the same as==, so it also returns false. - The default
toString()prints the class name,@, and a hexadecimal hash code, which tells a reader almost nothing. - The
HashSetkeeps both points and cannot find a newPointA(2, 3), because, as far as Java knows, they are all different. Stringalready overridesequals()to compare characters, which is why strings must always be compared withequals(), not==.
Overriding All Three
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class Main {
static final class Point {
private final int x, 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 other)) return false; // null or another type
return x == other.x && y == other.y; // compare the fields
}
@Override
public int hashCode() {
return Objects.hash(x, y); // equal points -> equal hash
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
record Pixel(int x, int y) {} // records generate all three
public static void main(String[] args) {
Point p1 = new Point(2, 3), p2 = new Point(2, 3);
System.out.println(p1 + " equals " + p2 + ": " + p1.equals(p2));
System.out.println("same hashCode: " + (p1.hashCode() == p2.hashCode()));
System.out.println("equals(null): " + p1.equals(null));
Set<Point> set = new HashSet<>();
set.add(p1);
set.add(p2);
System.out.println("set size: " + set.size() + ", contains Point(2, 3)? " + set.contains(new Point(2, 3)));
Map<Point, String> labels = new HashMap<>();
labels.put(new Point(0, 0), "origin");
System.out.println("lookup: " + labels.get(new Point(0, 0)));
Pixel a = new Pixel(5, 5), b = new Pixel(5, 5);
System.out.println(a + " equals " + b + ": " + a.equals(b));
}
}
Output
Point(2, 3) equals Point(2, 3): true
same hashCode: true
equals(null): false
set size: 1, contains Point(2, 3)? true
lookup: origin
Pixel[x=5, y=5] equals Pixel[x=5, y=5]: true
- A correct
equals()has three steps: return true for the same object, return false fornullor a different type (instanceofhandles both), then compare the fields that define equality. o instanceof Point otherchecks the type and creates the variableotherin one step (pattern matching, Java 16+).hashCode()must return the same number for equal objects.Objects.hash(x, y)combines the same fields used inequals.- Now the set holds one point and
containsworks, and aPointcan be used as aHashMapkey. toString()returns something a human can read, which is whatSystem.out.println, string concatenation and debuggers show.- A
recordgenerates all three methods from its components, asPixelshows. Use a record whenever a class is mainly a carrier of data.
The equals and hashCode Contract
| Rule | Meaning |
|---|---|
| Reflexive | x.equals(x) is true |
| Symmetric | If x.equals(y) then y.equals(x) |
| Transitive | If x equals y and y equals z, then x equals z |
| Consistent | Repeated calls give the same answer while the fields do not change |
| Null | x.equals(null) is false, never an exception |
| Hash code | Equal objects must have equal hash codes (unequal objects may share one) |
Hash collections first use hashCode() to pick a bucket, then equals() to compare within it. If equal objects have different hash codes, they land in different buckets and are never compared at all.
Common Mistakes
- Overriding
equalsbut nothashCode, which breaksHashSetandHashMap. - Writing
equals(Point o)instead ofequals(Object o). That overloads the method rather than overriding it;@Overridecatches this. - Changing a field used in
hashCodewhile the object is inside a hash set or used as a map key. The object becomes impossible to find. Make such fieldsfinal. - Comparing
doublefields with==insideequals; useDouble.compare(a, b) == 0.
Practice Exercises
Exercise 1. Write equals and hashCode for a Book class where two books are equal when their ISBN strings are equal.
Show answer
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book other)) return false;
return isbn.equals(other.isbn);
}
@Override
public int hashCode() {
return isbn.hashCode();
}
Exercise 2. Replace the Point class from the second example with a record. How many lines do you save?
Show answer
record Point(int x, int y) {}
One line replaces the fields, constructor, equals, hashCode and accessors, about 20 lines. The only difference is that the record’s toString() prints Point[x=2, y=3]; override it if you want another format.
Frequently Asked Questions
Should I use instanceof or getClass() in equals?
getClass() != o.getClass() treats a subclass as never equal to its parent, which keeps equals symmetric. instanceof is simpler and is safe when the class is final, as in the example. Many IDEs can generate either version.
Can my IDE generate these methods?
Yes. IntelliJ IDEA, Eclipse and VS Code can all generate equals, hashCode and toString from the fields you choose. For data classes, a record is even simpler.
Summary
==compares references;equals()should compare meaning.- Always override
equalsandhashCodetogether, using the same fields. - Override
toStringfor readable output and debugging. - Records generate all three automatically.
