1.

What Is The Difference In Using Instanceof And Getclass() Method For Checking Type Inside Equals?

Answer»

This question was asked multiple times, sometimes by looking at your equals() and hashCode implementation. Well, KEY difference COMES from the point that instanceof OPERATOR returns true, even if COMPARED with subclass e.g. Subclass instanceof Superclass is true, but with getClass() it's false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with subclass object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a.equals(b) is true than b.equals(a) should also be true. Just replace a and b with an INSTANCE of Superclass and Subclass, and you will end up breaking symmetry rule for equals() method.

This question was asked multiple times, sometimes by looking at your equals() and hashCode implementation. Well, key difference comes from the point that instanceof operator returns true, even if compared with subclass e.g. Subclass instanceof Superclass is true, but with getClass() it's false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with subclass object. While if you use instanceof operator, you end up breaking symmetry rule for equals which says that if a.equals(b) is true than b.equals(a) should also be true. Just replace a and b with an instance of Superclass and Subclass, and you will end up breaking symmetry rule for equals() method.



Discussion

No Comment Found