Java - Equals and Hashcode

Every object has the following two properties:
1. An ability to compare itself with any other object
2. A int value associated with it, which can have a business logic

There are a few basic rules to be applied for two objects to be equal:
  1. Consistency : If two objects are equal they should always be equal provided none of their values(which determine their equality) change
  2. Symmetry : If object1 equals object2, then object2 should equal object1, Same rule for non-equality
  3. Reflexive : If you compare an object with itself, it should always return true, under all circumstances
  4. Transitivity : If object1 equals object2, and object2 equals object3, then object1 should equal object3.
Why do we need equals method when we have ==?
== checks for reference equality (if two reference are same) equals method checks if two objects are equal or not

Just be sure of overriding equals method before using it. Else be ready for false, except when comparing same references :D

It is a good practice to override HashCode and Equals in your POJOs. Hashcode should have some business logic associated with it. Should be unique.
I really love using code which has comments, equals and hashcode overriden.

If two objects are equal (according to the equals methods), they need to have the same hashcode.
BUT the reverse is not always true. Two objects with the same hashcode need not be same.

Method Signatures
Equals Method and Hashcode overridden in a class:



Bottomline: Your POJOs should have equals and hashCode method overridde. Just define the parameters which determine the equality of two objects. And keep a check on the rules.

Coming soon: Hashcode and HashMaps.

Comments

Popular posts from this blog

Writing your own ejabberd Module

npm ECONNREFUSED error

Conditional Flow - Spring Batch Part 6