下面的代碼生成:
名稱的的hashCode
名稱的的hashCode
名稱的等於
ID = 0多個inherance,套裝和hashCode /等於首要
import scala.collection.mutable
object TestTraits {
def main(args: Array[String]): Unit = {
val toto0 = new Person(0,"toto")
val toto1 = new Person(1,"toto")
val peoples = mutable.Set.empty[PersonID]
peoples.add(toto0)
peoples.add(toto1)
peoples.foreach(_.showID)
//peoples.foreach(_.saySomething)//won't compile'
}
}
trait Name{
var theName=""
override def hashCode(): Int = {
println("Name's hashCode")
var hash = 5;
hash = 71 * hash + this.theName.##;
hash
//super.hashCode()//infinite loop
}
override def equals(that: Any): Boolean = {
println("Name's equals")
that match {
case that: Name => this.theName.equals(that.theName)
case _ => false
}
}
}
abstract class PersonID{
val idNumber: Int
override def hashCode(): Int = {
println("PersonID's hashCode")
super.##
}
override def equals(that: Any): Boolean = {
println("PersonID's equals")
that match {
case that: PersonID => this.eq(that)
case _ => false
}
}
def showID: Unit = {
println("ID=" + idNumber)
}
}
class Person(val id:Int, val s:String) extends {
val idNumber=id
} with PersonID with Name {
/*override def hashCode(): Int = {
println("Person's hashCode")
super.## //infinite loop !!
}
override def equals(that: Any): Boolean = {
println("Person's equals")
that match {
case that: Person => this.eq(that)
case _ => false
}
}*/
theName=s
def saySomething: Unit = {
print("Hello, my name is " + theName + ", ")
showID
}
}
由於 「人民」 是一組是PersonID的,我期待以下輸出:
PersonID的hashCode
PersonID的hashCode
ID = 0
ID = 1
有人可以解釋這種行爲,以及如何做我期望的(也就是說,有一個基於字段的值的「等於」的類除了將實例放入Set [PersonID] )
另一個謎就是爲什麼當我在自定義hashCode中使用super.hashCode()時會出現無限循環?
PS:我用一個預先初始化的抽象成員,因爲我需要它在我的實際使用情況......
感謝您的回答,現在很明顯,我必須以不同的方式實施。 – acapola 2011-05-04 10:46:18