Why can hashCode() return the same value for different objects in Java?

hashing an object means “finding a good, descriptive value (number) that can be reproduced by the very same instance again and again“. Because hash codes from Java’s Object.hashCode() are of type int, you can only have 2^32 different values. That’s why you will have so-called “collisions” depending on the hashing algorithm, when two distinct Objects … Read more

Probability of getting a duplicate value when calling GetHashCode() on strings

Large. (Sorry Jon!) The probability of getting a hash collision among short strings is extremely large. Given a set of only ten thousand distinct short strings drawn from common words, the probability of there being at least one collision in the set is approximately 1%. If you have eighty thousand strings, the probability of there … Read more

How to implement hashCode and equals method

in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this: /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (code == null ? 0 : code.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ … Read more

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

General advice and guidelines on how to properly override object.GetHashCode()

Table of contents When do I override object.GetHashCode? Why do I have to override object.GetHashCode()? What are those magic numbers seen in GetHashCode implementations? Things that I would like to be covered, but haven’t been yet: How to create the integer (How to “convert” an object into an int wasn’t very obvious to me anyways). … Read more