Wednesday 29 February 2012

Object class methods (Overriding equals() and hashCode())

What are the methods in object class
equals()
toString()
hashCode()
wait ()
notify()
notifyAll()
clone()
finalize()

Why toString needs to be overridden
If we use the object class’s toString method and try to print our object then it will print something like ClassName@hashcode which doesn’t provide any meaningful information
In order to provide meaningful information when object .toString is called toString must be overridden

Why equals need to be overridden?
If we create two objects having same state and compare it using obj1.equals(obj2) then it will always return false as these two objects are distinct object even though meaningfully they are equal as their state is equal
Therefore meaningfully compare two objects on their state we need to override equals method

What is hashCode?
As per Object class implementation of hashCode,HashCode is memory address of an object mapped to integer
Why we need to override hashCode method?
Actual hashCode is in symmetry with equals. There are some rules about symmetry
If equals returns true for two objects hashcode must be same
If equals returns false then hashCode can be same or different

If we are using our custom object as a key in hash base collection then it’s necessary to implement equals and hashCode methods
Because when we use put() method in hash based collection some hashing algorithm is applied over hashCode and the location of bucket to store the key value is identified
When we use get() method of hash based collections then first the location of bucket is found out using hashCode then the equals method is invoked to found out the actual equal object in the bucket

What the bucket implements?
Bucket actually implements the linked list

What if equals method is overriden and hashCode is not overridden?
If equals is overridden but hashCode is not then hashCode will inherit the implementation from Object class.
In Object class hashCode() is nothing but memory address of an object mapped to integer
Therefore even though two objects are meaningfully equal as equal returns true their hashCode will be always different as these are two different objects with different memory locations.
Therefore in hashbased collections if we use such object as a key then we will not able to retrieve the value. We will get null when we try to retrieve the value


What if equals method is overriden and returns false and hashCode is overridden but returns the same value 1?
This is perfectly valid.In this case different objects will be placed in same bucket in the next node of linked list
This will affect the performance while retrieving elements using get() from hash based collection
As get() method has to iterate through whole linked list and check the equals() method to find out actual object


No comments:

Post a Comment