Tuesday, September 13, 2016

Set Example : Mutable & Immutable Sets, HashSet...

  1. We have the option to select either Mutable or Immutable Set #87
  2. By default, Immutable Set will be used if we do not Specificy the Mutuable Set package
  3. Package
  4.     scala.collection.mutable
  5.     scala.collection.immutable
scala> /*
     |     Immutable Set example #88
     | */
     | //'var' is needed as this is an Immutable Set
     | var immutableSet = Set("English", "Math")
immutableSet: scala.collection.immutable.Set[String] = Set(English, Math)

scala> // Here += expands to mutableSet = mutableSet + "Physics"

scala> immutableSet += "Physics"

scala> immutableSet
res19: scala.collection.immutable.Set[String] = Set(English, Math, Physics)

scala>

scala> /*
     |     Mutable Set example #89
     | */
     | import scala.collection.mutable
import scala.collection.mutable

scala> val mutableSet = mutable.Set("English", "Math")
mutableSet: scala.collection.mutable.Set[String] = Set(Math, English)

scala> //Here += is actuall a method ; mutableSet.+=("Physics")

scala> mutableSet += "Physics"
res21: mutableSet.type = Set(Math, English, Physics)

scala> mutableSet
res22: scala.collection.mutable.Set[String] = Set(Math, English, Physics)

scala>

scala> /*
     |     Creating a Specific Implementation of Set
     |     Immutable HashSet
     | */
     | //'var' is needed as this is an Immutable Set
     | import scala.collection.immutable
import scala.collection.immutable

scala> var immutableSet = immutable.HashSet("English", "Math")
immutableSet: scala.collection.immutable.HashSet[String] = Set(English, Math)

scala> // Here += expands to mutableSet = mutableSet + "Physics"

scala> immutableSet += "Physics"

scala> immutableSet
res26: scala.collection.immutable.HashSet[String] = Set(Physics, English, Math)