Scala: Can I rely on the order of items in a Set?

后端 未结 3 2051
余生分开走
余生分开走 2020-12-01 13:40

This was quite an unplesant surprise:

scala> Set(1, 2, 3, 4, 5)       
res18: scala.collection.immutable.Set[Int] = Set(4, 5, 1, 2, 3)
scala> Set(1, 2,         


        
3条回答
  •  暖寄归人
    2020-12-01 14:18

    ListSet will always return elements in the reverse order of insertion because it is backed by a List, and the optimal way of adding elements to a List is by prepending them.

    Immutable data structures are problematic if you want first in, first out (a queue). You can get O(logn) or amortized O(1). Given the apparent need to build the set and then produce an iterator out of it (ie, you'll first put all elements, then you'll remove all elements), I don't see any way to amortize it.

    You can rely that a ListSet will always return elements in last in, first out order (a stack). If that suffices, then go for it.

提交回复
热议问题