Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

clarification needed for " overriding equals method and hashtable key "

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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
  • 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 ]
 
    Bookmark Topic Watch Topic
  • New Topic