user3366706
user3366706

Reputation: 1599

Scala Set - default behavior

Want to know how scala arranges the data in set.

scala> val imm = Set(1, 2, 3, "four")                  //immutable variable
imm  : scala.collection.immutable.Set[Any] = Set(1, 2, 3, four)

scala> var mu = Set(1, 2, 3, "four", 9)  
mu: scala.collection.immutable.Set[Any] = Set(four, 1, 9, 2, 3)

scala> mu += "five"

scala> mu.toString 
res1: String = Set(four, 1, 9, 2, 3, five)

Order remains as we insert in case of immutable Set but not in mutable Set. Also no matter how many times I create a new set with var xyz = Set(1, 2, 3, "four", 9) the order of getting stored remains same Set(four, 1, 9, 2, 3). So it's not storing in random, there is some logic behind it which I want to know. Moreover, is there any advantage of such behavior?

Upvotes: 1

Views: 110

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369614

Sets don't have an order. An item is in the set or it isn't. That's all you can know about a set.

If you require a certain ordering, you need to use an ordered set or possibly a sorted set.

Of course, any particular implementation of a set may or may not incidentally have an ordering which may or may not be stable across multiple calls, but that would be a purely accidental implementation detail that may change at any time, during an update of Scala or even between two calls.

Upvotes: 3

Related Questions