hashcode() and equals() are method of Object Class in Java.
Both methods represent identity of an object.
Now,what is the use of these methods ?
hashcode() -
Whenever an object is created ,an hashcode is assigned to it by java.
Hashcode is an integer value and it is returned by hashcode().
Hashtables and Hashmaps use this hashcode to store Objects in it.
equals() -
This method uses Object references to check equality of two objects.
Note**-
If one of this method is overridden then other must also be overridden.
Contract between hashcode() and equals()-
1.Whenever hashcode() is invoked more than once during execution of method,hashcode()
must give same value ,provided equals method is not modified during this method.
Means, if you place a object in hashmap and you want to get the same object passing key
then you cannot change the key of the same object in between put() and get() operation.
2. If 2 objects are equal then their hashvalues must be equal.
3. If 2 objects are not equal doesn't mean that 2 objects have different hashvalues.
Means 2 different objects can have equal hashcode.
Why do we need to override hashcode()?
Consider key in Hashmap of Integer class,which does not override hashcode().
Hashmap map = new Hashmap();
Imp Link-->
http://howtodoinjava.com/core-java/basics/working-with-hashcode-and-equals-methods-in-java/
Both methods represent identity of an object.
Now,what is the use of these methods ?
hashcode() -
Whenever an object is created ,an hashcode is assigned to it by java.
Hashcode is an integer value and it is returned by hashcode().
Hashtables and Hashmaps use this hashcode to store Objects in it.
equals() -
This method uses Object references to check equality of two objects.
Note**-
If one of this method is overridden then other must also be overridden.
Contract between hashcode() and equals()-
1.Whenever hashcode() is invoked more than once during execution of method,hashcode()
must give same value ,provided equals method is not modified during this method.
Means, if you place a object in hashmap and you want to get the same object passing key
then you cannot change the key of the same object in between put() and get() operation.
2. If 2 objects are equal then their hashvalues must be equal.
3. If 2 objects are not equal doesn't mean that 2 objects have different hashvalues.
Means 2 different objects can have equal hashcode.
Why do we need to override hashcode()?
Consider key in Hashmap of Integer class,which does not override hashcode().
Hashmap map = new Hashmap();
Imp Link-->
http://howtodoinjava.com/core-java/basics/working-with-hashcode-and-equals-methods-in-java/
No comments:
Post a Comment