HashMap Java Interview Questions

Q) What is hashing and how does hashmap work in java?
Java Hashmap works on the principle of Hashing, where only singe null key and multiple null values are allowed. Hashmap stores data as key and value pair.
Hashing is a technique in which a large object is converted to a small unique object that represents same object. A small value helps in faster indexing and searches. It internally uses a LinkedList to store key-value pairs. The load factor is hashmap is 0.75.
Objects in java hashmap are stored using the put() method and retrieved using the get() method. When we use put method hashcode method of function is called, which helps in finding bucket location. Key and Values are stored as Map.Entry object .


Q) Use of HashCode and equals Method?
 
Q) Difference between Hashtable and HashMap?
HashTable HashMap
Hashtable is synchronized.  Hashmap is not synchronized.
 HashTable does not allow any null keys or values.  Hashmap allows one null key and multiple null values.
 
 





Q)Difference between Hashtable and ConcuurentHashMap in java?
Concurrent HashMap  Hashtable
Concurrent HashMap Uses multiple buckets to store data. Hence avoids read lock. Hashtable uses the same bucket, hence it has a huge impact on performance.
When you read from a concurrent hashmap it will not have locks. Hashtable will have locks while reading as well.
Concurrent Hashmap was released after java 5. This is a legacy class from older versions of java.
Concurrent HashMap uses iterator which is fail-safe. This is fail-fast which throes concurrent modification exception.
It uses database shards logic, which is known as Concurrent-level. Hashtable locks completely.
This belongs to the Executor framework. Hashtable belongs to the Collection framework.

Q)Difference between ConcuurentHashMap and SynchronizedMap in java?
Both the maps are thread-safe and implement map interface. Below are the differences.
ConcuurentHashMap 
SynchronizedMap 
Concurrent Hashmap is threadsafe without synchronizing the while map, it uses the concept of lock Striping. This synchronizes the whole map and hence performance-wise not good.
While handling huge data this is faster. This is slower in performance compare to concurrent Hashmap.
What is ConcurrentSkipListMap ?
ConcurrentSkipListMap implements ConcurrentNavigableMap and uses skiplist which helps in maintaining order. So in short ConcurrentSkipListMap is concurrentHashmap with order.
Previous
Next Post »

Pages