I have the following two Maps in the REPL in Scala:
Case 1
scala> var a1=Map("a" -> "b", "c" -> "d", "e" -> "f", "g" -> "h")
a1: scala.collection.immutable.Map[String,String] = Map(a -> b, c -> d, e -> f, g -> h)
scala> var a2=Map("a" -> "b","c" -> "d","e" -> "f","g" -> "h","i" -> "j")
a2: scala.collection.immutable.Map[String,String] = Map(e -> f, a -> b, i -> j, g -> h, c -> d)
Both of the above examples print the same text in the REPL:
...
scala.collection.immutable.Map[String,String] = ...
But the following two examples show different output text:
Case 2
scala> a1.getClass.getName
res10: String = scala.collection.immutable.Map$Map4
scala> a2.getClass.getName
res11: String = scala.collection.immutable.HashMap$HashTrieMap
Why are the text outputs (scala.collection.immutable.Map$Map4 and scala.collection.immutable.HashMap$HashTrieMap) in the REPL different? What does the output text mean exactly? I know that Map with more than four elements uses HashMap instead of Map, but why are the output texts the same in case 1 (for variable a1 and a2), and different in case 2?
If you have a look in the reference documentation, you can read that a HashTrieMap is the default implementation of an immutable map.
However, Scala has a further optimization for immutable sets and maps that contain less than five elements. Sets and maps with one to four elements are stored as single objects that just contain the elements (or key/value pairs in the case of a map) as fields - that is why you see the class Map4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With