tigga4392
tigga4392

Reputation: 111

scala map += operator with five pairs

I am having an issue with appending pairs to an existing Map. Once I reach the fifth pair of the Map, the Map reorders itself. The order is correct with 4 pairs, but as soon as the 5th is added it shifts itself. See example below (assuming I built the 4 pair Map one pair at a time.):

scala> val a = Map("a1" -> 1, "a2" -> 1, "a3" -> 1, "a4" -> 1)
a: scala.collection.immutable.Map[String,Int] = Map(a1 -> 1, a2 -> 1, a3 -> 1, a4 -> 1)

scala> a += ("a5" -> 1)
scala> a
res26: scala.collection.immutable.Map[String,Int] = Map(a5 -> 1, a4 -> 1, a3 -> 1, a1 -> 1, a2 -> 1)

The added fifth element jumped to the front of the Map and shifts the others around. Is there a way to keep the elements in order (1, 2, 3, 4, 5) ?

Thanks

Upvotes: 2

Views: 331

Answers (1)

Anton
Anton

Reputation: 2341

By default Scala's immutable.Map uses HashMap.

From http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html:

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

So a map is really not a table that contains "a1" -> 1, but a table that contains hash("a1") -> 1. The map reorders its keys based on the hash of the key rather than the key you put in it.

As was recommended in the comments, use LinkedHashMap or ListMap: Scala Map implementation keeping entries in insertion order?

PS: You might be interested in reading this article: http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/

Upvotes: 3

Related Questions