Posts

Showing posts from October, 2015

Java - Equals and Hashcode

Image
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: Consistency : If two objects are equal they should always be equal provided none of their values(which determine their equality) change Symmetry : If object1 equals object2, then object2 should equal object1, Same rule for non-equality Reflexive : If you compare an object with itself, it should always return true, under all circumstances 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