jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes implementation pf equals in a hashmap..?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "implementation pf equals in a hashmap..??" Watch "implementation pf equals in a hashmap..??" New topic
Author

implementation pf equals in a hashmap..??

abhishek pendkay
Ranch Hand

Joined: Jan 01, 2007
Posts: 184
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..???


The significant problems we face cannot be solved by the same level of thinking which created them – Einstein
SCJP 1.5, SCWCD, SCBCD in the making
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
abhishek pendkay
Ranch Hand

Joined: Jan 01, 2007
Posts: 184
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

Joined: Oct 27, 2005
Posts: 19653
    
  18

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: implementation pf equals in a hashmap..??
 
Similar Threads
Why Hashtable not allowing null key values?
Overriding hashCode()
equals() & hashCode()
best way to iterate a generic list
HashMap entries with duplicate keys...