• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

clarification needed for " overriding equals method and hashtable key "

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All ,

could anyone please explain me of what it means by

" If you dont override the equals method , you wont be able to use the object as a key in the hash table " .

Though I have gone through the explanation given in scjp 1.4 ( K&B ) certification book , Iam not quite clear on this one . It will be a great help if anyone explain this more elaborately .

Thanks in Advance.
Regards,
Prathibha.
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by prathibha ananthapadmanabha:
Hi All ,

" If you dont override the equals method , you wont be able to use the object as a key in the hash table " .


if you don't override the equals(), then the Object class equals() will be called..and Object class equals() only returns true if the two reference variable refer to the same object.

Ex:




If you decide that two car object are equal if they have the same vin then you have to override the equals(), because if you don't then when you will call the equals() then the Object class equals() will only check for references.

Hence when we comment the equals() at line 1 then we get false as the Object class equals() check whether obj1 and obj2 refers to the same object or not.

But on uncommenting we get true because the overriden equals() gets called.

So in case of HashTable if you don't override equals() in your class, then there is no way your two objects created using new operator will be considered meaningfully equal. Hence you cannot use them as key in HashTable i.e on commenting the equals() in the above example the Car object cannot be used as key because they are never meaningfully equal.
[ September 03, 2007: Message edited by: Priyam Srivastava ]
 
no wonder he is so sad, he hasn't seen this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic