Core JavaInterview questionsJava

Java Collections Interview questions

Difference between HashTable and HashMap

  • HashMap is not threadsafe whereas HashTable is threadsafe
  • Since HashMap is not synchronized it performs better than HashTable
  • Hashtable does not allow null key, hashmap allows 1null key & several null values
  • Iterator in hashmap is fail-fast. But enum in Hashtable is not fail-fast
  • Fail-fast means if one thread is iterating over a map and another is trying to modify it by adding/deleting elements, it will throw ConcurrentModificationException.


How HashMap works

  • HashMap works on the principle of hashing
  • we have put() and get() methods to store and retrieve data from hashmap
  • it has a number of buckets which stores key-value pairs
  • when put() is called, hashmap implementation calls hashcode() on the key to identify the bucket location… then stores both key+value in the bucket
  • when get() is called, the hashcode() on key is used to identify the bucket location and the value if returned.
  • If two key objects have same hashcode, bucket location will be the same and collision occurs in hashmap.
  • Inside the bucket, data is stored in linked list, so in collision scenario, it will get added to next node.
  • So, when get() is called, the hashcode() would point to the bucket location, then the use key.equals() to find the correct node in the linked list.


Synchronizing HashMap

  • HashMap can be synchronized by calling Collections.getSynchronizedMap(hashmap);



  • Best suited when you have multiple readers and few writers. Otherwise, performance degrades to synchronized map or hashtable
  • allows multiple users to read simultaneously without any blocking
  • this is achieved by partitioning map into different parts depending on concurrency level and locking only a portion of the map during updates.
  • Since update operations like put(), remove(), putall(),clear() are not synchronized, concurrent retrieval may not reflect most recent change on the map.
  • All operations on concurrent hashmap are threadsafe.



  • creates a copy of underlying arraylist with every mutating operation ,i.e. add or set.
  • Normally very expensive as it involves costly array copy with every write operation. Use when iteration is more than mutation.
  • threadsafe
  • iterator is fail-safe



  • map implementation that stores only weak references to its keys
  • this allows a key-value pair to be garbage collected when key is no longer reachable by any thread
  • useful for implementing “registry” like data structures where the utility of the entry vanishes when its no longer referenced


Why return type of hashcode() is int and not long ?

  • The maximum length of an array is Integer.MAX_VALUE


  • Since the primary use of hashcode() is to determine in which slot to insert an object into the backing array of hashtable/hashmap, a hashcode greater than Integet.MAX_VALUE can not be stored in an array


Sorted vs Ordered Collections

When a collections is ordered, it means you can iterate through the collection in a specific order,

A Hashtable collection is not ordered, where as an ArrayList is ordered by elements index position and LinkedHashMap is ordered by the insertion order.

Some collections keep an order referred as natural order of elements.. those collections are not just ordered, they are sorted. The natural order is specified the Comparable interface. But it is also possible to define other sort orders using Comparator interface



Why String, Integer and other wrapper classes are considered good keys ?

String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because 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, If you can  keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.


Can we use any custom object as key in HashMap ?

We can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If custom object is Immutable than this will be already taken care because you can not change it once created.


Can we use ConcurrentHashMap in place of Hashtable ?

Hashtable is synchronized but ConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced as Hashtable and can be used in place of it but Hashtable provide stronger thread-safety than ConcurrentHashMap.


How HashMap  works in Java

HashMap  works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap  uses linked list in case of collision and object will be stored in next node of linked list.

Also HashMap  stores both key+value tuple in every node of linked list.


What will happen if two different HashMap  key objects have same hashcode?

They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap .


Why we need ConcurrentHashMap and CopyOnWriteArrayList

The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List. However, several factors make them unsuitable for use in highly concurrent applications  for example their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.


ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.


Difference between ConcurrentHashMap and Hashtable

Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation , no matter how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.


Difference between ConcurrentHashMap and Collections.synchronizedMap

ConcurrentHashMap is designed for concurrency and improve performance while HashMap which is non synchronized by nature can be synchronized by applying a wrapper using Collections.synchronizedMap.


© 2015, All rights reserved.

3 thoughts on “Java Collections Interview questions

Comments are closed.