Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and hashCode()

 
Preethi Enukonda
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone give a detailed description on equals() and hashcode()with a simple example
[ March 30, 2008: Message edited by: Preethi Enukonda ]
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Preethi,

unfortunately the full concept of equals() and hashCode() and how they can be implemented can't be said in a few words.

In short equals() is used to compare to objects for equality. The default implementation just compares the objects for identity which is the same you'd get if you used the == operator. If this isn't satisfying you could override equals. The overridden equals() should meet some rules in order to work as expected.

hashCode() is primarily important if you want to use an object as a key for one of the hash based collection classes. Writing a really good hashing functions isn't trivial so I can't explain here in detail. Anyway you should always override hashCode() if you have overridden equals() for your objects to work correctly.

Unfortunately you will have to read a bit about it. Here's a good article from Brian Goetz which explains most things you'll need to know.

Marco
[ March 30, 2008: Message edited by: Marco Ehrentreich ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic