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