• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why we implement hashcode and equals() method while working with Hashtable and hashMap ?

 
Praveen Kumar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchies,


Why we want to implement the hashcode() and equals() method when you dealing with objects in HashTable abd HashMap. That is main Question and could you please
direct me good material on this topic.

Please please

Thansk
Praveen

 
Francesc Martinez
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because HashXXX classes uses hashCode() to find objects.

Javadoc in these classes should explain something about that. I also highly recommend the book "Effective Java" for this and other important matters.

You can look for information about hash tables. How they work, how objects are indexed using the "hash code" for quick access.
 
Stephan van Hulst
Bartender
Pie
Posts: 6128
74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's good practice to always override hashCode() and equals(Object), even if you're not going to use a HashTable or something similar, as long as it makes sense.

For instance, if two of your objects are always distinct, then you don't have to override these methods, because Object already provides the correct implementation.
 
Soumyajit Hazra
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For instance, if two of your objects are always distinct

How the java runtime will understand that the object are distinct or how the jre will tell two user defined objects are equal?
The object class equals only check for references. Say for example for a Employee class objects may be treated equals depending on there dept and experience property not by looking at reference only.
 
Stephan van Hulst
Bartender
Pie
Posts: 6128
74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly, and this is why you would override the equals method. A lot of classes use the equals method to see when two objects are distinct or equal. You can override this method to provide your own understanding of when two objects are equal.

Keep in mind that whenever you override equals, you *must* override hashCode as well. Take a good look at the documentation for these methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic