6

Title basically says it all. I've tried Googling but return a load of false positives. I guess I'm just wondering if there was a certain rationale behind these two specific numbers or could they have easily been many other sets of numbers?

Edit: And, since the source of the numbers has been answered, any reason why writers of the Boolean hashCode method used those numbers (besides that they're prime)? Would any other set of prime numbers worked just as well?

AHungerArtist
  • 9,332
  • 17
  • 73
  • 109

5 Answers5

6

These numbers come from the official Boolean API.

Beau Grantham
  • 3,435
  • 5
  • 33
  • 43
4

Hash functions are prone to collisions. The number of collisions can be reduced by using prime numbers (think about the factors prime numbers have). 1231 and 1237 are both prime numbers.

/e1
After doing a little more research I came across this:

Since they most probably will have no common divisors with the hashtable size (unless the prime itself divises the hashtable size), the chances of collision in common hashtable implementations would be minimized.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • So there's nothing special about these two, just that they're prime? So, 11 and 17 would be just as good? – AHungerArtist Nov 22 '11 at 22:10
  • @AHungerArtist The larger the prime, the safer the function will be. As far as I know, this has its roots in cryptography where large prime numbers were multiplied together to generate even larger (and fairly secure) keys for codes. – Jeffrey Nov 22 '11 at 22:14
  • 2
    @AHungerArtist As it turns out, the larger the prime the larger the hashtable has to be before there will be a collision. In this situation, the hashtable would have 2462 (2 * 1231) buckets before a collision would occur. Why the developers of java chose *these* primes would be a question best left to them. – Jeffrey Nov 22 '11 at 22:40
3

They're apparently short-cutting calling the Java core Boolean class hashCode() results.

Returns: the integer 1231 if this object represents true; returns the integer 1237 if this object represents false.

A far more in-depth discussion (albeit one that ends up just with suppositions and not hard-and-fast facts) can be found here.

Mike
  • 7,994
  • 5
  • 35
  • 44
1

They come from the Boolean hashCode method. They are just 2 large arbitrary prime numbers. See Boolean.hashCode()

Community
  • 1
  • 1
Andy
  • 8,841
  • 8
  • 45
  • 68
1

That still begs the question as to where those came from and why.

Perhaps it is they are best estimates of number of steps from someone's office to the staff cafeteria. Or someone's girl-friend's phone number. Who knows.

The bottom line is that unless you track down the original (Sun) authors and ask them, you will never know the real answer. (I'm assuming that they can still remember the real answer, and are prepared to tell you!)

Lets move along ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216