0

When I was trying to insert an element to a scala mutable set, I got the following output.

My code was as follows.

object sets{
  def main(args:Array[String]):Unit={
    var set1 = Set(1,2,3,4);
    println(set1);
    println(set1.+(6));
  }
}

And the output was as follows.

Set(1,2,3,4)
Set(1,6,2,3,4)

Is there a specific reason for 6 being printed after 1 instead of after 4?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
NipuniYR
  • 39
  • 5

2 Answers2

3

The order in the set does not depend on when you insert the elements. To be fair, the idea of order in a set does not really make sense since a set is an unordered collection.

If you want to understand why you see this order, this has to do with the hashcode of the objects. I recommend reading the Wikipedia article about Hashtables.

If you need to preserve the order in which you insert your object, you could use a List. To keep the uniqueness of the elements inside your collection, you can use List.distinct.

Paul Renauld
  • 186
  • 6
2

LinkedHashSet preserves the order of insertion like so

val set1 = LinkedHashSet(1,2,3,4)
println(set1)
println(set1 += 6)

which outputs

LinkedHashSet(1, 2, 3, 4)
LinkedHashSet(1, 2, 3, 4, 6)

as explained here

You need to preserve the order in which the items are inserted. Then you use the LinkedHashSet. Practically as fast as the normal HashSet, needs a little more storage space for the additional links between elements.

Note LinkedHashSet, like other sets, will not keep duplicates, that is,

assert(set1 == (set1 += 1)) // passes

If you do not require uniqueness of elements, then consider going with List.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98