I’m very confused by Scala’s HashSet and Set types as they both seem to do the same thing.
- What is the difference between them?
- Is it the same in Java?
- In my reference it says that
HashSetis an “explicit set class” (as compared toSet). What does that mean?
Scala’s mutable and immutable
HashSetimplementations are concrete classes which you can instantiate. For example, if you explicitly ask for a newscala.collection.immutable.HashSet, you will always get a set which is implemented by a hash trie. There are other set implementations, such asListSet, which uses a list.Setis a trait which all the set implementations extend (whereas in Java,Setis an interface).Setis also a companion object* with anapply** method. When you callSet(...), you’re calling this factory method and getting a return value which is some kind ofSet. It might be aHashSet, but could be some other implementation. According to 2, the default implementation for an immutable set has special representation for empty set and sets size up to 4. Immutable sets size 5 and above and mutable sets all use hashSet.*In Scala, instead of having static class methods, you can create a singleton
objectwith the same name as your class or trait. This is called a companion object, and methods you define on it can be called asObjectName.method(), similar to how you’d call a static method in Java.**
Set(x)is syntactic sugar forSet.apply(x).