• 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
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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 ]
 
Seriously? That's what you're going with? I prefer this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic