I ran into an interesting (and very frustrating) issue with the equals()
method today which caused what I thought to be a well tested class to crash and cause a
the instanceOf
statement is often used in implementation of equals.
This is a popular pitfall !
The problem is that using instanceOf
violates the rule of symmetry:
(object1.equals(object2) == true)
if and only if (object2.equals(object1))
if the first equals is true, and object2 is an instance of a subclass of the class where obj1 belongs to, then the second equals will return false!
if the regarded class where ob1 belongs to is declared as final, then this problem can not arise, but in general, you should test as follows:
this.getClass() != otherObject.getClass();
if not, return false, otherwise test
the fields to compare for equality!