Scala: Contains in mutable and immutable sets

前端 未结 2 2139
说谎
说谎 2021-02-20 17:42

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

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-20 18:24

    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.

提交回复
热议问题