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:

  1. a hashmap array of special objects hold both key , value.
  2. the array has amount of buckets (slots), 16.
  3. the hashing algorithm provided hashcode() method every object has. therefore, when writing new class, should take care of proper hashcode() , equals() methods implementation. default 1 (of object class) takes memory pointer number. that's not of classes use. example, string class 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 same hashcode().
  4. 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.
  5. 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 tell maps how many buckets you'll use if know in before.
  6. if tries value, provides key, hash it, mod it, , go through potential linked list exact match.

an image, courtesy of wikipedia: the graphics

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

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -