• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

implementation pf equals in a hashmap..??

 
abhishek pendkay
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i dont implement my own equals method in a hashmap what will the default equals method do.. will it do an == test or will it compare the hashcodes of the tow objects..???
 
Rob Spoor
Sheriff
Pie
Posts: 20559
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap, HashSet and Hashtable all use the hash code first to find all objects with that same hash code, then use equals to find the right one.*

If you don't override equals, and you inherit it from Object, then it uses == for the equality check. The hash code will be some hash code created by the JVM; how is not important. All you need to know is that that hash code, which you can also retrieve for any object using System.identityHashCode(), is unique for each different object.


* This is the reason that when you override equals(), you should also override hashCode().
 
abhishek pendkay
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Rob even i say the same thing... but i just had an argument with a very senior person in my company and he insists that in case of Maps the default implementation will not an == test it will check the hashcode of both the objects... is there any logic to it..???
 
Rob Spoor
Sheriff
Pie
Posts: 20559
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well it will use the hashCode, but seeing as different objects can have the same hashCode that will not necessarily be sufficient. It will then use equals(), which may or may not use ==.

Keep in mind however, that if the equals method uses == that you need the very same object to retrieve the value for the key. Also, the key cannot change in such a way that hashCode changes, because then it will be positioned in the wrong bucket*, and it can never be found until you fix the hashCode. That's why Strings are so popular for keys - they can never change, and their equals method allows different String objects to be used for lookups as long as they represent the same String.

* A bucket is the term for objects with the same hash code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic