i having issue appending pairs existing map. once reach fifth pair of map, map reorders itself. order correct 4 pairs, 5th added shifts itself. see example below (assuming built 4 pair map 1 pair @ time.):
scala> val = 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> += ("a5" -> 1) scala> res26: scala.collection.immutable.map[string,int] = map(a5 -> 1, a4 -> 1, a3 -> 1, a1 -> 1, a2 -> 1) the added fifth element jumped front of map , shifts others around. there way keep elements in order (1, 2, 3, 4, 5) ?
thanks
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 order of map; in particular, not guarantee order remain constant on time
so map not table contains "a1" -> 1, table contains hash("a1") -> 1. map reorders keys based on hash of key rather key put in it.
as recommended in comments, use linkedhashmap or listmap: scala map implementation keeping entries in insertion order?
ps: might interested in reading article: http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/
Comments
Post a Comment