I am using Scala 2.11.
I have a case class Dimension and I created 3 instances of it. When I put them into a HashSet, I surprisingly found that only 1 was added properly. Then I tried to debug and found out they had the same hashCode.
I am new to Scala, but have a lot of experience in Java. I am wondering why all of them are having the same hashCode even if they have different fields and what is the default implementation of hashCode method in Scala's case class? And how does HashSet/HashMap work in Scala?
Here is my code example.
object Echo {
def main( args:Array[String] ):Unit = {
var d1 = new Dimension
d1.name = "d1"
d1.dimensionId = "1"
println("d1:" + d1.hashCode()) // d1, d2, d3 have the same hashCode
var d2 = new Dimension
d2.name = "d2"
d2.dimensionId = "2"
println("d2:" + d2.hashCode())
var d3 = new Dimension
d3.name = "d3"
d3.dimensionId = "3"
println("d3:" + d3.hashCode())
var l = List(d1, d2, d3)
val categories = mutable.HashSet.empty[Dimension]
l.foreach(md => {
categories += md
})
println(categories.size) // size is 1
}
}
case class Dimension() {
var dimensionId: String = _
var name: String = _
}