equals, hashCode and toString
Override equals and hashCode together and toString for readable output.
Example
public class Main {
static class P {
int id; P(int id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof P p && p.id == id; }
@Override public int hashCode() { return Integer.hashCode(id); }
@Override public String toString() { return "P#" + id; }
}
public static void main(String[] args) {
P a = new P(1), b = new P(1);
System.out.println(a.equals(b) + " " + (a == b) + " " + a);
}
}Result
true false P#1
Exercise
Compare values.
a.(b)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.