~/ learn/ java-from-zero/ cards/ equals & hashCode done right
1 of 4

Type a correct equals override using instanceof pattern matching

Type a correct equals override using instanceof pattern matching

Answer

@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point p)) return false; return x == p.x && y == p.y; }

The identity check short-circuits the common case. instanceof with a pattern variable safely handles null (instanceof null is always false) and binds p for field access in one step. No NPE risk.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e17f6566-5fd0-4dc0-a6b0-8b23459362fb/flashcard utf-8 LF