Scala collection Set is not adding Elem as expected

34 views
Skip to first unread message

Nishan Patel

unread,
Aug 21, 2016, 6:41:15 AM8/21/16
to scala-internals
Hi All,

I'm using Scala 2.11.7 with JDK 1.8 and from the REPL when I'm trying to created mutable and immutable set with 5-6 element, when I was getting result it is automatically giving element in wrong order.

Please see below image for more details. 

For mutable Set: When I was adding 1 to 6 it gives set as res0: Set(1,5,2,6,3,4) instead of Set(1,2,3,4,5,6)

Same as for immutable Set: When I was adding 1 to 6. it gives res1: Set(5,1,6,2,3,4)

Both mutable and immutable set is working and giving correct order until I add element upto 4. When I add 5th elem it gives returning set in wrong order.

Looks like it is a bug in collection, if not please let me know why it is behaving like  this.













Thanks,
Nishan Patel

Sébastien Doeraene

unread,
Aug 21, 2016, 6:46:47 AM8/21/16
to scala-internals
Hello,

It is not a bug. Sets, as well as Maps, are unordered collections. The order of their elements is not guaranteed. If you need a set that preserves insertion order, there is LinkedHashSet:
http://www.scala-lang.org/api/2.11.8/index.html#scala.collection.mutable.LinkedHashSet

Cheers,
Sébastien

--
You received this message because you are subscribed to the Google Groups "scala-internals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-internals+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nishan Patel

unread,
Aug 21, 2016, 6:48:50 AM8/21/16
to scala-internals
Thanks I got it. 
To unsubscribe from this group and stop receiving emails from it, send an email to scala-interna...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages