• 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
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

About the advantages of overriding equals()

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Hi,


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).


Thanks,
[ May 27, 2007: Message edited by: Chandra Bhatt ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!