Thursday 15 August 2013

java - Inevitable Collisions When Hashing? -



java - Inevitable Collisions When Hashing? -

if create new map:

map<integer,string> map = new hashmap<integer,string>();

then phone call map.put() bunch of times each unique key, say, 1000000 times, there ever collision or java's hashing algorithm guarantee no collisions if key unique?

hashing not guarantee there no collisions if key unique. in fact, thing that's required objects equal have same hashcode. number of collisions determines how efficient retrieval (fewer collisions, closer o(1), more collisions, closer o(n)).

what object's hashcode depends on type is. instance, string's default hashcode is

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

which simplifies downwards complexity of string single number -- possible reach same hashcode 2 different strings, though it'll pretty rare.

if 2 things hash same thing, hashmap uses .equals determine whether particular key matches. that's why it's of import override both hashcode() , equals() , ensure things equal have same hash code.

java map hashmap

No comments:

Post a Comment