Question

In scala, why does toSet() method mix up the order of elements in a collection (ListBuffer)?

Which collection can I use to both secure uniqueness of each element and keep their original order?

Was it helpful?

Solution

Because the set abstraction, being a subclass of the traversable, has no guarantees about the order of elements held within:

A traversable class might or might not have two properties: strictness and orderedness. Neither is represented as a type.
 ...
 If the class is not ordered, foreach can visit elements in different orders for different runs (but it will keep the same order in the same run).'

More precisely about why the elements get 'mangled': the toSet method constructs a new set collection out of some existing collection. It uses the default set implementation for this new set collection. The default set implementation is based on a hash table. In a hash table, the order of elements is undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top