That depends on the Set you are using. If you do not know which Set implementation you have, then the answer is simply, no you cannot be sure. In practice I usually encounter the following three cases:
-
I need the items in the Set to be ordered. For this I use classes mixing in the
SortedSettrait which when you use only the Standard Scala API is always aTreeSet. It guarantees the elements are ordered according to theircompareTomethod (see theOrderedtrat). You get a (very) small performance penalty for the sorting as the runtime of inserts/retrievals is now logarithmic, not (almost) constant like with theHashSet(assuming a good hash function). -
You need to preserve the order in which the items are inserted. Then you use the
LinkedHashSet. Practically as fast as the normalHashSet, needs a little more storage space for the additional links between elements. -
You do not care about order in the Set. So you use a
HashSet. (That is the default when using theSet.applymethod like in your first example)
All this applies to Java as well, Java has a TreeSet, LinkedHashSet and HashSet and the corresponding interfaces SortedSet, Comparable and plain Set.