Scala LinkedHashMap.toMap 保留顺序? [英] Scala LinkedHashMap.toMap preserves order?

查看:55
本文介绍了Scala LinkedHashMap.toMap 保留顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如标题所述,将 LinkedHashMap 转换为 Map 会保留元素的存储顺序吗?

As the title states, does converting a LinkedHashMap to a Map preserve the order in which elements are stored?

我不相信,但找不到任何证据.

I believe not, but couldn't find any evidence.

或者,Scala 中是否有任何不可变 Map 的实现可以保留元素插入的顺序?

Alternatively, is there any implementation of an immutable Map in Scala that preserves the order in which elements are inserted?

推荐答案

通用的 Map 接口没有这样的排序保证.也不能,因为这会排除 HashMap 作为可能的实现.

The generic Map interface makes no such guarantee of ordering. Nor can it, as this would then rule out HashMap as a possible implementation.

我相信 collection.immutable.ListMap 会保留插入顺序,您也可以通过 Map 接口使用 LinkedHashMap,这样可以防止访问任何mutator方法.通过明确指定类型,这很容易做到:

I believe collection.immutable.ListMap preserves insertion order, you could also use a LinkedHashMap via the Map interface, which would then prevent access to any mutator methods. This is easy enough to do by explicitly specifying the type:

val m: scala.collection.Map[Int,Int] = collection.mutable.LinkedHashMap(1->2, 2->3)

或(使用类型归属):

val m = collection.mutable.LinkedHashMap(1->2, 2->3) : Map[Int,Int]

这篇关于Scala LinkedHashMap.toMap 保留顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆