java - How HashTable and HashMap key-value are stored in the memory? -
i understand there hashing technique applied key store value in memory address.
but don't understand how collision happening here? which hashing algorithm java use create memory space? md5?
the basic idea of hashmap this:
- a
hashmaparray of special objects hold both key , value. - the array has amount of buckets (slots), 16.
- the hashing algorithm provided
hashcode()method every object has. therefore, when writing newclass, should take care of properhashcode(),equals()methods implementation. default 1 (ofobjectclass) takes memory pointer number. that's not of classes use. example,stringclass uses algorithm makes hash characters in string - think of this:hashcode = 1.char + 2.char + 3.char...(simplified). therefore, 2 equal strings, though on different location in memory, have samehashcode(). - the result of
hashcode(), "132", number of bucket object should stored if had array big. don't, ours 16 buckets long. use obvious calculation'hashcode % array.length = bucket'or'132 mod 16 = 4', store key-value pair in bucket number 4. - if there's no other pair yet, it's ok.
- if there's 1 key equal key have, remove old one.
- if there's key-value pair (collision), chain new 1 after old 1 linked list.
- if backing array becomes full, have make many linked lists, make new array doubled length, rehash elements , add them new array, dispose old one. expensive operation on
hashmap, want tellmapshow many buckets you'll use if know in before. - if tries value, provides key, hash it, mod it, , go through potential linked list exact match.
an image, courtesy of wikipedia: 
in case,
- there array 256 buckets (numbered, of course, 0-255)
- there 5 people. hashcodes, after being put through
mod 256, point 4 different slots in array. - you can see sandra dee didn't have free slot, has been chained after john smith.
now, if tried telephone number of sandra dee, hash name, mod 256, , bucket 152. there you'd find john smith. that's no sandra, further ... aha, there's sandra chained after john.
Comments
Post a Comment