Method equals

The documentation of set says "sets contain no pair of elements e1 and e2 such that e1.equals(e2)". The equals method returns true if the e1 and e2 are in some way equal. It may be different from two objects being identical. There can be two distinct objects that are equal. For example, we could have a color implementation that has the name of the colors as an attribute and two color objects may return true calling the equals method on one of them and passing the argument as the other when the two strings are equal. The default implementation of the equals method is in the code of the Object class and this returns true if and only if e1 and e2 are exactly the same and single object.

It seems to be obvious, but my experience shows that it cannot be stressed enough that the implementation of equals in an object has to be as follows:

  • Reflexive: This means that an object that always equals itself
  • Symmetric (commutative): This means if e1.equals(e2) is true, then e2.equals(e1) should also be true
  • Transitive: This means if e1.equals(e2) and e2.equals(e3), then e1.equals(e3)
  • Consistent: This means that the return value should not change if the objects were not changed between the invocations
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.151.164