hash collision and the HashMap

  • Follow


If I have a HashMap<String,MyObject>, then the HashMap uses the hash of the String to place MyObject in its internal storage. If the hash for a String is the same as another String, then what?I assume that the hash collision mechanism uses toString() to resolve which String you are specifying.OK so far.Now if I have a HashMap<MyKey,MyObject), then the HashMap uses the hash of MyKey. What if this also produces a collision? If the toString() is used, and I have not provided a MyKey specific toString(), then the default toString() is the class name plus the hash.In that case I over-write the previous MyKey entry.Or am I missing something....-- Wojtek :-)
0
Reply Wojtek 3/26/2007 7:40:55 PM

Wojtek schrieb:> Or am I missing something....> indeed..a Hashmap rather maps the hashcode  of the key to a list of  key- Valuetuples ..it then uses the equals method in that list to find what object you arereally searchingso hashmap is kind of an array of lists.. the hashcode helps you to findthe right list in the array then equals is used to find the right key inthe list which has the mapped object in its tuple.Christian
0
Reply Christian 3/26/2007 7:54:15 PM


Christian wrote :> Wojtek schrieb:>>> Or am I missing something....>> > it then uses the equals method in that list to find what object you are> really searchingAh ha. A light dawns...Thanks-- Wojtek :-)
0
Reply Wojtek 3/26/2007 8:07:53 PM

Wojtek wrote:> Christian wrote :>> Wojtek schrieb:>>>>> Or am I missing something....>>>>> it then uses the equals method in that list to find what object you are>> really searching> > Ah ha. A light dawns...toString() does not figure into the collision resolution.-- Lew
0
Reply Lew 3/26/2007 9:47:42 PM

Wojtek wrote:> If I have a HashMap<String,MyObject>, then the HashMap uses the hash of > the String to place MyObject in its internal storage. If the hash for a > String is the same as another String, then what?There are several ways of dealing with collisions in hashing structures.The one the Java developers choose to use for HashMap is to have bucketsthat can each contain multiple entries.Equal hash code entries go in the same bucket, just as they would ifthey had different hash codes that mapped to the same bucket.Each bucket contains zero or more entries. Each entry contains both keyand value, so that equals() can be used to distinguish unequal keys withequal hash codes.> I assume that the hash collision mechanism uses toString() to resolve > which String you are specifying.You lost me at this point. Why do you think toString() would be any usefor hash collision resolution?In any case, take a look in your JDK install directory. There should bea file there called "src.zip". Read java/util/HashMap.java in that zip.Patricia
0
Reply Patricia 3/26/2007 10:14:38 PM

4 Replies
332 Views

(page loaded in 0.002 seconds)

Similiar Articles:





7/24/2012 3:49:37 PM


Reply: