Video in progress
What is the difference between writing equals with instanceof and with getClass(), and what does it lead to when subclasses end up in a HashSet?
With instanceof, a subclass object can be equal to its parent, but if the subclass adds its own field, symmetry breaks. getClass() preserves symmetry, but subclasses such as Hibernate proxies end up not equal to their "original". The choice depends on the class hierarchy.
📖 Answer
Breaking symmetry:
class Point {
final int x, y;
// constructor and hashCode omitted for brevity
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
}
class ColorPoint extends Point {
final String color;
@Override public boolean equals(Object o) {
return o instanceof ColorPoint c && super.equals(c) && c.color.equals(color);
}
}
point.equals(colorPoint); // true
colorPoint.equals(point); // false
Inside HashSet.contains(x), x.equals(stored) is called. So the result depends on which object is in the Set and which is the argument: with the same data it comes out "present" in one place and "absent" in another. A bug like that is very hard to find from logs.
With getClass() != o.getClass(), Point and ColorPoint are never equal, so the contract stays clean. But the problem shows up elsewhere: the lazy proxy of a Hibernate entity has a different class (Order$HibernateProxy$...), and it is not equal to the real Order. As a result, one order can sit in a Set<Order> twice.
Practical rules:
- for value classes, use a
recordor afinalclass: no inheritance, so no question; - if you need inheritance, make
equalsfinalin the parent class, write it withinstanceof, and forbid subclasses from adding new "equality fields"; - in entities, compare with
instanceofand through getters, because a proxy's fields may not be populated.
Sign up to mark studied questions and save your progress.