Skip to main content

Posts

Showing posts from August, 2011

Understanding Equals and hashCode contract,and what can go wrong

SO what about Equals and hashcode?
Most people will say these are the two basic function available in Object class and could be called from any Class object created in Java. Well thats true but there is more then this.
First take a look at HashCode:
Every JVM provides a good hashCode implementation mostly based on the object's memory location and for two different object(by location) it produce different hashCode.
And at the same time Equal method also consider two different memory location object as Not Equal. So at core two are in a contract and works great.

But as soon as start writing code and write a class and create a state of a class(means create few data variables in a class), the core contract of hashCode and Equal doesnt work any more.
e.g.
Class MyFirstCLass{ int value; public MyFirstCLass(int value){ this.value = value; } } MyFistCLass obj1 = new MyFirstCLass(10); MyFistCLass obj2 = new MyFirstCLass(10);
Now obj1 and obj2, theoratically should be equal as both holds …