HashMap and Map in scala


What is the difference between HashMap and Map in scala  please give me some real time sceanrio 

1 Answer(s)


Hi Rakesh,

scala.collection.Map is the interface for immutable maps while scala.collection.HashMap is a concrete implementation.

Creating with Map() or Map.empty gives a special empty singleton map, with Map(a -> b) with up to 4 pairs yields specialized classes for such small maps, and 5 and upwards gives you scala.collection.HashMap.

HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to small String that represents same String. A shorter value helps in indexing and faster searches.

Some points on HashMap:

  • HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value.
  • HashMap allows null key also but only once and multiple null values.
  • This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. It is roughly similar to HashTable but is unsynchronized.

Internal Structure of HashMap

Internally HashMap contains an array of Node and a node is represented as a class which contains 4 fields :

  1. int hash
  2. K key
  3. V value
  4. Node next

HashMap is preferrably used where you want the key values to be unque while storing information.
For examples:

  • To populate dropdown list in your form (key as a dropdown option value, value as dropdown option displayText)
  • To Implement Phonebook (Name - Number)
  • To implement Dictionary Application (Word - Meaning, Description)

Hope this helps.