Overriding the java equals() method - not working?

后端 未结 8 1247
花落未央
花落未央 2020-11-22 02:33

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

8条回答
  •  遇见更好的自我
    2020-11-22 03:17

    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!

提交回复
热议问题