Object, toString, equals and hashCode
Every class extends Object. Override toString for readable output, equals for logical equality and hashCode consistently so collections work.
Example
import java.util.*;
public class Main {
static class P {
final String n; final int a;
P(String n, int a) { this.n = n; this.a = a; }
@Override public String toString() { return n + "(" + a + ")"; }
@Override public boolean equals(Object o) { return o instanceof P p && p.n.equals(n) && p.a == a; }
@Override public int hashCode() { return Objects.hash(n, a); }
}
public static void main(String[] args) {
P x = new P("Ada", 21), y = new P("Ada", 21);
System.out.println(x + " " + x.equals(y) + " " + (x == y));
Set<P> set = new HashSet<>(List.of(x)); set.add(y);
System.out.println(set.size());
}
}Result
Ada(21) true false 1
Exercise
Readable text for an object.
public String ()
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.