我希望這個答案不會重復,我嘗試過搜索,但我認為以前沒有人問過。
從我可以閱讀的 Scala 檔案(https://docs.scala-lang.org/overviews/scala-book/case-classes.html ):
...
`equals` and `hashCode` methods are generated, which let you compare objects and easily use them as keys in maps.
...
所以我有這個代碼:
class Person_Regular(name: String)
case class Person_CC(name: String)
如果我列印結果hashCode():
println(Person_CC("a").hashCode())
我可以在控制臺中看到:
-1531820949
這是有道理的,因為 case 類hashCode默認包含該方法。普通班呢?
這段代碼:
println((new Person_Regular("Joe")).hashCode())
還列印哈希碼:
1018937824
那么在定義一個class方法hashCode的時候也是自動生成的嗎?那么為什么 Scala 檔案說它hashCode是用案例類生成的,而普通類已經這樣做了呢?
uj5u.com熱心網友回復:
那么在定義一個類時,方法 hashCode 也是自動生成的嗎?
不,對于普通的類,它只是繼承自java.lang.Object/ AnyRef,它是基于物件的身份,而不是它的內容:
class A(name: String)
case class B(name: String)
println(A("x").hashCode != A("x").hashCode) // true: hash codes are different
println(B("x").hashCode == B("x").hashCode) // true: hash codes are the same
在第一種情況下,允許哈希碼不同,因為物件在參考上不相等。
在第二種情況下,哈希碼以可預測的方式從案例類的內容中派生出來,因此是相同的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512159.html
標籤:斯卡拉哈希码
