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

About the advantages of overriding equals()

Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I need some clarifications regarding, if i override the equals() for my class and when i create some objects and i add them into hashtable means, if some of my objects are CONCEPTUALLY equal means,
I want to know, before adding them into the hashtable, whether equals() will be invoked and the objects wont be get added into the hashtable if they are CONCEPTUALLY equal.
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Person p1 = new Person("Jill");
Person p2 = new Person("Jill");

If you override the equals() method for the Person class, then using
p1.equals(p2) returns true, otherwise false.

What you call conceptually equals, I know it as meaningfully equals.
Two objects are meaningfully equal if state of the both object is same.
In our Person class, example, both person objects are encapsulating name as "Jill" so they can be treated equal only when you override the equals method.

For your objects to be used as key in the HashMap/Hashtable or so
you must override the hashCode() method too along with equals() method.
hashCode is used to decide which bucket to put the object into and
equals method is used to decide whether the object is already in the Map
and picking the right object from the bucket while retrieving object from
the bucket (it is possible that more than one object is put on the same
bucket because their hashCode(s) are same, although it should not be).

[ May 27, 2007: Message edited by: Chandra Bhatt ]
I can't take it! You are too smart for me! Here is the tiny ad:
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic