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

sdk*_*ldf 3 collections scala set listbuffer

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

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

axe*_*l22 12

因为作为遍历的子类的集合抽象无法保证在其中保存的元素的顺序:

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).'
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你需要元素唯一性,那么就有`mutable.LinkedHashSet`集合.其中的元素按其添加顺序遍历. (3认同)