为什么“toSet”会这样?方法混淆了 ListBuffer 中元素的顺序?

发布于 2024-12-05 06:49:28 字数 117 浏览 2 评论 0原文

在Scala中,为什么toset()方法混合集合中的元素顺序(listBuffer)?

我可以使用哪个集合来确保每个元素的独特性并保留其原始订单?

In scala, why does toSet() method mix up the order of elements in a collection (ListBuffer)?

Which collection can I use to both secure uniqueness of each element and keep their original order?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我为君王 2024-12-12 06:49:28

因为 set 抽象,是 < 的子类a href="http://www.scala-lang.org/api/current/scala/collection/Traversable.html" rel="noreferrer">traversable,不保证其中保存的元素的顺序:

A traversable class might or might not have two properties: strictness and orderedness. Neither is represented as a type.
 ...
 If the class is not ordered, foreach can visit elements in different orders for different runs (but it will keep the same order in the same run).'

更准确地说明元素为何会出现'mangled':toSet 方法从某些现有集合构造一个新的 set 集合。它使用这个新集合集合的默认集合实现。默认集实现​​基于哈希表。在哈希表中,元素的顺序是未定义的。

Because the set abstraction, being a subclass of the traversable, has no guarantees about the order of elements held within:

A traversable class might or might not have two properties: strictness and orderedness. Neither is represented as a type.
 ...
 If the class is not ordered, foreach can visit elements in different orders for different runs (but it will keep the same order in the same run).'

More precisely about why the elements get 'mangled': the toSet method constructs a new set collection out of some existing collection. It uses the default set implementation for this new set collection. The default set implementation is based on a hash table. In a hash table, the order of elements is undefined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文