Saturday, December 29, 2012

Java HashMap

HashMap:
DEFAULT_INITIAL_CAPACITY = 16;
DEFAULT_LOAD_FACTOR = 0.75f;
1. put(key,value)
HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic.
Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value )  will be stored in LinkedList.
       if (size++ >= threshold)
           resize(2 * table.length);
there is potential race condition exists while resizing HashMap in Java


2. get(key)
HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object
If two Value objects are stored in same bucket, we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.

hashcode() is used in all situations and equals() come in picture only in case of retrieving value object from HashMap in Java. Using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap  keys and improve performance of Java HashMap  by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.

if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety

3. ConcurrentHashMap and Hashtable
ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
ConcurrentHashMap like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



No comments:

Post a Comment