I\'ve discovered a strange behavior for mutable sets which I cannot understand:
I have a object which I want to add to a set. The equals method for the class is overridd
You need to override hashCode
as well. hashCode
is essential to override when you override equals
.
Note there were also a few things that didn't compile, so I edited a bit more:
class Test(val text:String){ // added val
override def equals(obj:Any) = obj match {
case t: Test => if (t.text == this.text) true else false
case _ => false
}
override def toString = text
override def hashCode = text.hashCode
}
val mutableSet:scala.collection.mutable.Set[Test] = scala.collection.mutable.Set.empty
mutableSet += new Test("test")
println(mutableSet)
println(mutableSet.contains(new Test("test")))
val immutableSet:scala.collection.immutable.Set[Test] = scala.collection.immutable.Set.empty
val immutableSet2 = immutableSet + new Test("test") // reassignment to val
println(immutableSet2)
println(immutableSet2.contains(new Test("test")))
I recommend reading http://www.artima.com/pins1ed/object-equality.html for a lot more insights on doing object equality. It's eye opening.