MY mENU


Wednesday 30 January 2013

Equals() Method


Using “==” operator – it always compares objects with their referecnces.
Using “equals” method- it compares objects based on its implementation.

Why equals() method is specially given when == operator is already doing the objects comparison operation?
  • == operator will only compare reference of the objects.
  • Real world objects must be compared with their state.
  • For this purpose == operator should be overloaded.
  • Since java does not support operator overloading.
  • We need an alternative to == operator.
  • Hence equals() method is given by sun to provide.
  • object state comparison logic” by developer if need as per project requirement.
  • And every object may not contain state.

Object class developer does not know the sub class required object state comparison logic.

Hence it is the sub class developer’s responsibility to override equals() to compare subclass objects with their state.

If equals() method is overridden then hashCode() method must be overridden with below contract:

If equals() method return true by comparing two objects, then hashCode of the both objects must be same.

If it returns false, the hashCode() of the both objects may or may not be same.

No comments:

Post a Comment