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

“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 … Read more

Why might a System.String object not cache its hash code?

Obvious potential answer: because that will cost memory. There’s a cost/benefit analysis here: Cost: 4 bytes for every string (and a quick test on each call to GetHashCode). Also make the string object mutable, which would obviously mean you’d need to be careful about the implementation – unless you always compute the hash code up-front, … Read more

Is there a way to auto-generate GetHashCode and Equals with ReSharper?

Yes, Resharper can do that. With cursor inside your type, open the “Generate code” menu (Alt+Ins depending on settings or Resharper -> Edit -> Generate Code), and select “Equality members”: This opens a window where you can select which members are used for equality, along with some options about the generated code (e.g. should your … Read more

HashCode giving negative values

I don’t think hash values should be negative. Why not? It’s entirely valid to have negative hash codes. Most ways of coming up with a hash code naturally end up with negative values, and anything dealing with them should take account of this. However, I’d consider a different approach to coming up with your hash … Read more

Why does the equals method in String not use hash?

Hashcode could be a first-round check for inequality. However, it presents some tradeoffs. String hashcodes are lazily calculated, although they do use a “guard” value. If you’re comparing strings with long lifetimes (ie, they’re likely to have had the hashcode computed), this isn’t a problem. Otherwise, you’re stuck with either computing the hashcode (potentially expensive) … Read more

tech