Java Interview : Why use a HashMap?

HashMap is meant to store key value pair. So if you have a situation where you need to store a key-value pair, like let key be “milk” and value be 2 (packets) then use a Map like hashmap to store it as milk-2 (k-v). The Dictionary is the best example to replicate a hash-map use-case. If duplicate keys are not required, for example if tomorrow someone finds out sun is not a star but a planet, and inserts that in a hashmap it will override the last sun value and you will have a new value but still one sun. The same thing done in a list will give you 2 suns in the list.
As hashing comes into picture, retrieval is faster and better than Lists. But there is no ordering maintained in a Hash based collection, rehashing can change the order  anytime too.
Java Interview : HashMap in Java
Java Interview : HashMap in Java

Just to refresh hashing(running some logic) a value gives you a integer which is used as an index to store the data in that location in an underlying array.Sometimes when you run this logic on different objects you get the same number, so to make you afraid we will call this term as Collision, now to solve this we make a linked list of these 2 same hash-code producing objects and attach it to the same index on the array.
Sometimes the interviewers want to know whats a good hashing function, even asking you to write it down. Although not many guys write hashing functions themselves and IDE gives you best implementation of a hashing function, some points might be helpful to remember here:
  1. A hash procedure must be deterministic—meaning that for a given input value it must always generate the same hash value.
  2. A good hash function should map the expected inputs as evenly as possible over its output range.
  3. It is often desirable that the output of a hash function have fixed size
  4. “A hash function that is used to search for similar (as opposed to equivalent) data must be as continuous as possible; two inputs that differ by a little should be mapped to equal or nearly equal hash values.”
So remember these points and crack that interview.

Comments

Popular posts from this blog

Java Interview : Threads

Spring Framework Interview Notes : Part Two Wiring

Card Dealer In Java in Less than 5 minutes