Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

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

What is the difference between methods ## and hashCode?

They seem to be outputting the same values no matter which class or hashCode overloading I use. Google doesn't help, either, as it cannot find symbol ##.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...