Part 08 / Topic 5 of 12
The Object class: toString, equals and hashCode
Every class you write, even with no extends, secretly extends java.lang.Object. That gives you three methods for free, with defaults that are rarely what you want: toString() (an unreadable class-name-plus-hash-code string), equals(Object) (true only if it is the exact same object), and hashCode() (a number consistent with that same-object equals). Overriding them is how a class describes "what makes two of me equal" and "how do I print myself" in its own terms.
Think of two ₹500 notes with different serial numbers: they are not the same note, but for spending purposes they are equal — "same object" and "equal value" are different questions, and Object's defaults only answer the first one.
Real-world example: a BankAccount where two objects with the same account number should count as the same account.
static class BankAccount {
private final String accountNumber; // two accounts are "equal" if this matches
private double balance;
BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
@Override
public String toString() {
return "BankAccount[" + accountNumber + ", balance=₹" + balance + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BankAccount)) return false;
BankAccount other = (BankAccount) o;
return accountNumber.equals(other.accountNumber);
}
@Override
public int hashCode() {
return Objects.hash(accountNumber);
}
}
PlainAccount toString(): true
PlainAccount p1.equals(p2): false (same data, but Object.equals checks identity)
a1 = BankAccount[SBIN0001234, balance=₹5000.0]
a2 = BankAccount[SBIN0001234, balance=₹9000.0]
a1.equals(a2): true (equal because the account number matches)
a1.hashCode() == a2.hashCode(): true
HashSet size after adding both: 1 (a2 is treated as a duplicate of a1)
(The first line checks that PlainAccount's default toString() starts with ObjectMethods$PlainAccount@, the Class$NestedClass@hashcode shape every un-overridden toString() has — not worth printing in full, since the hash code half changes every run.)
Three rules, the same ones Part 14 of the Python course calls out for __eq__/__hash__, because the rule is the same in both languages:
- If you override
equals, overridehashCodetoo — using the same fields. Otherwise two "equal" objects can land in differentHashMap/HashSetbuckets and the collection stops finding them. @Overrideon all three is not required by the compiler, but write it anyway: it is a compile error if you misspellequalsor get a parameter type wrong, catching the single most common bug in this section (writingequals(BankAccount other)instead ofequals(Object o), which silently overloads instead of overriding and is never called by collections).- Base equality on fields that do not change while the object sits in a
HashSet/HashMapkey — here,accountNumber, neverbalance.
Full program: examples/ObjectMethods.java.
Done here? The practice set for Part 8 — including the solutions — is on the part page.