views:

167

answers:

3
+9  Q: 

Boolean.hashCode()

Now I see how to implement a method hashCode() for the Boolean object:

public int hashCode() {
 return value ? 1231 : 1237;
}

And I wonder why it returns a values 1231 or 1237, why not something else?

+4  A: 

These two numbers are sufficiently big prime numbers. Please read the article on Hash Table on Wikipedia for further info.

Boris Pavlović
What is it in the wikipedia article that's relevant for this question? Could you post a citation?
aioobe
+7  A: 

1231 and 1237 are just two (fairly large) arbitrary prime numbers. Any other two large prime numbers would do fine.

They are well suited as hash codes as it is unlikely that they accidentally map to the same bucket in, say, a hash set. The greatest common divisor of the number of buckets and some large prime-number is 1 (unless the number of buckets happens to equal a multiple of the prime number in question).

Besides, this only matters if you're storing Booleans together with other objects, since Booleans only have two distinct instances (two different Boolean values will always return unique hash-codes) or when using them in a larger, composite, hash code.

aioobe
`why not other large prime nos used?` Here is list of all prime no? http://mindprod.com/jgloss/primes.html under 10,000, can you please explain this
org.life.java
I suppose these are sufficiently large. To get a gcd greater than 1, you'd need at least `2*1231 = 2462` buckets. Are collisions a problem in such a situation?
aioobe
+1 it is useful.
org.life.java
Interesting though that they are not really "fairly large" considering what can fit into an int. I suppose they are just big enough to work well with the JDK Hashtable, but still small enough to minimize calculation costs.
Thilo
Yes, it struck me too that they're not *that* large. But do you believe there is a higher cost with larger primes?
aioobe