Why is there no mutable TreeMap in Scala?

2019-02-03 22:48发布

Is it lack of time, some technical problem or is there a reason why it should not exist?

5条回答
在下西门庆
2楼-- · 2019-02-03 23:27

It's just a missing case that will presumably eventually be filled in. There is no reason not to do it, and in certain cases it would be considerably faster than the immutable tree (since modifications require log(n) object creations with an immutable tree and only 1 with a mutable tree).


Edit: and in fact it was filled in in 2.12.

Mutable TreeMap.

(There is a corresponding Set also.)

查看更多
Bombasti
3楼-- · 2019-02-03 23:33

There may be performance reasons for a mutable TreeMap, but usually you can use an immutable map in the same way as you would a mutable one. You just have to assign it to a var rather than a val. It would be the same as for HashMap, which has mutable and immutable variants:

val mh = collection.mutable.HashMap[Int, Int]()
var ih = collection.immutable.HashMap[Int, Int]()
mh += (1 -> 2)
ih += (1 -> 2)
mh // scala.collection.mutable.HashMap[Int,Int] = Map(1 -> 2)
ih // scala.collection.immutable.HashMap[Int,Int] = Map(1 -> 2)
查看更多
smile是对你的礼貌
4楼-- · 2019-02-03 23:35

I assume that the reason is that having a mutable variant doesn't bring a big benefit. There are some cases mentioned in the other answers when a mutable map could be a bit more efficient, for example when replacing an already existing value: A mutable variant would save creation of new nodes, but the complexity would be still O(log n).

If you want to keep a shared reference to the map, you can use ImmutableMapAdaptor which wraps any immutable map into a mutable structure.

查看更多
贪生不怕死
5楼-- · 2019-02-03 23:41

You'll also notice that TreeSet doesn't have a mutable equivalent either. It's because they share the common base class RedBlack, and the underlying data structure that keeps the Trees ordered by elements or keys is a red-black tree. I don't know too much about this data structure, but it's pretty complex (insertion and removal are pretty expensive compared to other Maps), so I assume that had something to do with a mutable variant not being included.

Basically, it's probably because the underlying data structure isn't readily mutable so TreeMap isn't. So, to answer your question, it's a technical problem. It can definitely be done though, there's just not much of a use case for it.

查看更多
地球回转人心会变
6楼-- · 2019-02-03 23:47

Meanwhile you can use the Java TreeMap, which is exactly what you need.

val m = new java.util.TreeMap[String, Int]()
m.put("aa", 2)
m.put("cc", 3)
查看更多
登录 后发表回答