Equality
equals and hashCode live as a pair.
For objects, == compares references. equals compares meaning if someone wrote it. String and record have it. A class with only public fields does not have it by default: two User objects named Ann are different until you describe equality.
The contract: if equals says yes, hashCode must match. Otherwise HashMap and HashSet break. The reverse is not true: an equal hash does not promise equality. Generate both methods together; do not edit just one.
Objects.equals(a, b) survives null on either side. a.equals(b) crashes if a is null. At the edge of a service, where a field might not have arrived, use Objects. Inside, where the constructor has already ruled out null, you can call equals directly.
Do not compare different types "roughly". equals usually returns false at once if the class differs. Casting through a shared interface without a rule is a source of quiet bugs in tests.
Practice
What to write together
Which method must agree with equals?
- toString
- hashCode
- wait
- clone
A safe call
You need to compare two strings, and either may be null. Which static method from Objects fits? Write the method name.
Same text
Write static String same(String a, String b). Return yes if the text matches, otherwise no. null on one side is no; two nulls are yes.