What is the difference between `##` and `hashCode`?

前端 未结 4 1210
陌清茗
陌清茗 2020-11-30 04:53

What is the difference between methods ## and hashCode?

They seem to be outputting the same values no matter which class or hashCode

4条回答
  •  野性不改
    2020-11-30 05:18

    "Subclasses" of AnyVal do not behave properly from a hashing perspective:

    scala> 1.0.hashCode
    res14: Int = 1072693248
    

    Of course this is boxed to a call to:

    scala> new java.lang.Double(1.0).hashCode
    res16: Int = 1072693248
    

    We might prefer it to be:

    scala> new java.lang.Double(1.0).##
    res17: Int = 1
    
    scala> 1.0.##
    res15: Int = 1
    

    We should expect this given that the int 1 is also the double 1. Of course this issue does not arise in Java. Without it, we'd have this problem:

    Set(1.0) contains 1 //compiles but is false
    

    Luckily:

    scala> Set(1.0) contains 1
    res21: Boolean = true
    

提交回复
热议问题