Does Scala automatically change order of data in sets?

Viewed 249

I was looking at a set example for scala and I noticed that when states3 was created the compiler changed the order of the members of that set, Wyoming was in 3rd place and now its last. Could someone please explain why this happens?

scala> val states = Set("Alabama", "Alaska", "Wyoming")
states: scala.collection.immutable.Set[String] = Set(Alabama, Alaska, Wyoming)
scala> val states2 = states + "Virginia"
states2: scala.collection.immutable.Set[String] =
Set(Alabama, Alaska, Wyoming, Virginia)
scala> val states3 = states2 + ("New York", "Illinois")
states3: scala.collection.immutable.Set[String] =
Set(Alaska, Virginia, Alabama, New York, Illinois, Wyoming)

example taken from Programming Scala: Scalability = Functional Programming + Objects by Dean Wampler

2 Answers

Set on its own guarantee only, that the same element cannot be inserted twice (by the same we understand true result of ==/.equals comparison with .hashcode matching .equals to filfil the contract). If your type is just Set, there are no guarantees about tha order which most likely means that it will be HashSet which optimizes internal structure towards easy .hashcode comparison.

If you want to preserve order of inserting (assuming that the same element inserted twice won't change the order of its first insertion) then use ListSet.

If you want to order element according to some Ordering use SortedSet.

Does Scala automatically change order of data in sets?

No, it doesn't for the simple reason that Sets don't have an order, and you can't change something that doesn't exist.

Note that this is nothing specific to Scala, or even to programming. That's part of the nature of sets in general.

Related