Jacob Sonia wrote:Hi,
I read this in kathy sierra book:
When using HashSet or LinkedHashSet, the objects you add to them
must override hashCode(). If they don’t override hashCode(), the default Object.
hashCode() method will allow multiple objects that you might consider "meaningfully
equal" to be added to your "no duplicates allowed" set.
But what i understand that if you override equals but do not override hashcode, then all the objects will land in the same bucket which will take more memory space and higher time to find the object, but why will it land objects that are meaningfully equal coz they are nowhere related to equals method.
If you override equals() and do NOT override hashCode(), the hashCode() method of Object class will be called, and it will assign different hashCode even if the objects are meaningfully equal.
For example if you have a Dog{} class and you override equals() and do NOT override hashCode() and you added two Dog() objects to a HashSet, two objects will be having different hashCode(), even if the equals() return true! So both Dog() objects are considered NOT duplicate and the size() returns 2.
Consider the following code which DOES NOT override hashCode()
The output will be something like
Dog name = Fluffy hashCode = 11394033 Dog name = Fluffy hashCode = 1671711
But if you decide LATER to override hashCode(), see the code below:
The output will be:
Dog name = Fluffy hashCode = 2107367690
(there is only ONE "Fluffy"
hope this is clear
SCJP6, SCWCD5, OCP-JBCD5, OCE-JWSD6 OCE-JPAD6 , OCM-JEA5 1,OCM-JEA5 2,3,OCJP8 - Brainbench certifications: J2EE, Java2, Java2-NonGUI, JSP, SQL2000 Admin, SQL2000 Programming , Brainbench certified Java Programmer, Computer Programmer, Web Developer, Database Administrator