为什么'toSet'方法会混淆ListBuffer中元素的排序?

时间:2011-09-19 18:54:09

标签: scala collections set listbuffer

在scala中,为什么toSet()方法会混淆集合中元素的顺序(ListBuffer)?

我可以使用哪个集合来确保每个元素的唯一性并保持原始顺序?

1 个答案:

答案 0 :(得分:11)

因为作为set的子类的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).'

更确切地说,为什么元素被“损坏”:toSet方法从一些现有集合构造一个新的集合集合。它使用此新集合集的默认集合实现。默认设置实现基于哈希表。在哈希表中,元素的顺序是未定义的。