2

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

Greasy Chicken
  • 107
  • 1
  • 9
  • 6
    Sets do **not** guarantee order. They guarantee to answer the question if an element is a member of the set or not. – Mario Galic Jun 25 '20 at 18:54
  • 1
    You can use a Set that is specifically ordered, but most likely, if you use a HashSet or something like that, it'll be kind of ordered according to the hashcode and not the order of insertion. See [Scala default Set Implementation](https://stackoverflow.com/questions/26901866/scala-default-set-implementation) and [Can I rely on the order of items in a Set](https://stackoverflow.com/questions/5245713/scala-can-i-rely-on-the-order-of-items-in-a-set) – user Jun 25 '20 at 19:00
  • @MarioGalic thank you that really helped clear things up for me – Greasy Chicken Jun 25 '20 at 19:16

2 Answers2

5

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.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
5

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653