3
在scala中,为什么toSet()
方法混淆了集合中元素的顺序(ListBuffer
)?为什么'toSet'方法混淆了ListBuffer中元素的排序?
哪个集合可以用来保证每个元素的唯一性并保持其原始顺序?
在scala中,为什么toSet()
方法混淆了集合中元素的顺序(ListBuffer
)?为什么'toSet'方法混淆了ListBuffer中元素的排序?
哪个集合可以用来保证每个元素的唯一性并保持其原始顺序?
因为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
方法构造了一个从现有的一些收藏中收集新的集合。它使用这个新集合集合的默认集合实现。默认设置实现基于哈希表。在散列表中,元素的顺序是未定义的。
如果您需要元素唯一性,则有'mutable.LinkedHashSet'集合。其中的元素按照添加的顺序遍历。 – axel22