hashCode() : Regular Class vs case Class

Scala compiler generates many methods including hashCode() method for case Class
scala> // Regular Class example

scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> class RegularClass(var1: Int, va2: String)
defined class RegularClass

scala> val obj1 = new RegularClass(1, "one")
obj1: RegularClass = $iwC$$iwC$RegularClass@dbdbeb5

scala> obj1.hashCode()
res41: Int = 230538933

scala> val obj2 = new RegularClass(1, "one")
obj2: RegularClass = $iwC$$iwC$RegularClass@1421c757

scala> obj2.hashCode()
res42: Int = 337758039

scala> val myMap = new HashMap[RegularClass, String]
myMap: scala.collection.mutable.HashMap[RegularClass,String] = Map()

scala> val m1 = myMap + (obj1 -> "firstobject")
m1: scala.collection.mutable.Map[RegularClass,String] = Map($iwC$$iwC$RegularClass@dbdbeb5 -> firstobject)

scala> val m2 = m1 + (obj2 -> "secondobject")
m2: scala.collection.mutable.Map[RegularClass,String] = Map($iwC$$iwC$RegularClass@dbdbeb5 -> firstobject, $iwC$$iwC$RegularClass@1421c757 -> secondobject)

scala>
     | // case Class example

scala> import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap

scala> case class MyCaseClass(var1: Int, va2: String)
defined class MyCaseClass

scala> val obj1 = new MyCaseClass(1, "one")
obj1: MyCaseClass = MyCaseClass(1,one)

scala> obj1.hashCode()
res44: Int = 1311424316

scala> val obj2 = new MyCaseClass(1, "one")
obj2: MyCaseClass = MyCaseClass(1,one)

scala> obj1.hashCode()
res45: Int = 1311424316

scala> val myMap = new HashMap[MyCaseClass, String]
myMap: scala.collection.mutable.HashMap[MyCaseClass,String] = Map()

scala> val m1 = myMap + (obj1 -> "firstobject")
m1: scala.collection.mutable.Map[MyCaseClass,String] = Map(MyCaseClass(1,one) -> firstobject)

scala> //Because both obj1 & obj2 are considered to be the same

scala> // key ; obj1 is overwritten by obj2

scala> val m2 = m1 + (obj2 -> "secondobject")
m2: scala.collection.mutable.Map[MyCaseClass,String] = Map(MyCaseClass(1,one) -> secondobject)

No comments:

Post a Comment