Lesson 6 of 10
equals(), hashCode() & toString()
Three methods every class should override: toString() for readable output, equals() for value-based comparison, and hashCode() for correct behaviour in HashSet and HashMap. Java's default implementations compare memory addresses - almost never what you want for domain objects.
Why Override All Three
- toString() default: Book@1b6d3586 - useless. Override to show meaningful field values.
- equals() default: == (reference equality). Two Book objects with the same ISBN are equal by VALUE - override accordingly.
- hashCode() contract: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Always override hashCode when you override equals.
- Break the contract → HashSet/HashMap silently lose objects - a production bug that's very hard to debug.
Implementing equals, hashCode & toString
import java.util.Objects;
public class Book {
private final String isbn;
private String title;
private double price;
public Book(String isbn, String title, double price) {
this.isbn = isbn;
this.title = title;
this.price = price;
}
// toString - human-readable (used in System.out.println, logs, debuggers)
@Override
public String toString() {
return String.format("Book{isbn='%s', title='%s', price=%.2f}", isbn, title, price);
}
// equals - ISBN is the natural identity of a book
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // same reference → equal
if (obj == null || getClass() != obj.getClass()) return false; // type check
Book other = (Book) obj; // safe cast
return Objects.equals(isbn, other.isbn); // compare by ISBN only
}
// hashCode - MUST be consistent with equals
@Override
public int hashCode() {
return Objects.hashCode(isbn); // same field as equals
}
public static void main(String[] args) {
Book b1 = new Book("978-0132350884", "Clean Code", 39.99);
Book b2 = new Book("978-0132350884", "Clean Code", 39.99);
Book b3 = new Book("978-0134685991", "Effective Java", 44.99);
System.out.println(b1.equals(b2)); // true - same ISBN
System.out.println(b1.equals(b3)); // false - different ISBN
System.out.println(b1 == b2); // false - different objects in memory
System.out.println(b1); // Book{isbn='978-0132350884', title='Clean Code', price=39.99}
// Correct behaviour in collections
var set = new java.util.HashSet<Book>();
set.add(b1);
set.add(b2); // duplicate by isbn - only 1 entry if hashCode+equals correct
System.out.println(set.size()); // 1
}
}Quick Quiz
Tip
Tip
Practice equals hashCode toString in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for equals(), hashCode() & toString()
Practice Task
Note
Practice Task - (1) Write a working example of equals hashCode toString from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with equals hashCode toString is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Three methods every class should override: toString() for readable output, equals() for value-based comparison, and hashCode() for correct behaviour in HashSet and HashMap.
- toString() default: Book@1b6d3586 - useless. Override to show meaningful field values.
- equals() default: == (reference equality). Two Book objects with the same ISBN are equal by VALUE - override accordingly.
- hashCode() contract: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Always override hashCode when you override equals.
Finished this lesson?