Java Source World A Java quick reference blog
What will happen if we don’t override the hashcode method
If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.
JVM assigns unique hashcode value to each object when they are created in memory
if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.
The answer to the question is for the hash technique based data structures like HashMap and HashTable.
Every object is placed in Hash bucket depending on the hashcode they have It is not necessary that every different object must have different hashcode hashcode is used to narrow the search result
When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method.
If two objects are same then HashMap will not add that key instead it will replace the old value by new one.
For more info please read:
Core java: How HashMap works in Java
Other posts you may like:
How HashMap works in Java
Equals() and Hashcode() in java
Serialization in java
It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.
JVM assigns unique hashcode value to each object when they are created in memory
if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.
equals() method is used to compare objects that they are having same value or not but why should we override the hashcode method ?
The answer to the question is for the hash technique based data structures like HashMap and HashTable.
Every object is placed in Hash bucket depending on the hashcode they have It is not necessary that every different object must have different hashcode hashcode is used to narrow the search result
When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method.
If two objects are same then HashMap will not add that key instead it will replace the old value by new one.
For more info please read:
Core java: How HashMap works in Java
Other posts you may like:
How HashMap works in Java
Equals() and Hashcode() in java
Serialization in java
No comments:
Post a Comment