wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Jason Bloch's hashCode formula Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Jason Bloch Watch "Jason Bloch New topic
Author

Jason Bloch's hashCode formula

Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
In the book Effective Java, Jason Bloch proposed this hashCode formula (here shown for strings). What is the significance of the magic numbers 17 and 37 ? Is some number theory math wizardry involved ?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,
It's Joshua Bloch!
Other than their being prime numbers, there's no special significance to them; they're just values that empirically work well.


[Jess in Action][AskingGoodQuestions]
Rocky Summers
Ranch Hand

Joined: Nov 07, 2003
Posts: 66
hi! just wondering what
this.value and this.value.hashCode() is...
Gavin Bong
Ranch Hand

Joined: Apr 25, 2003
Posts: 56
value and code are the two member variables in my class, from which this code extract was taken from.
Mac Lai
Greenhorn

Joined: Jan 14, 2003
Posts: 3
Hi,
I try to use the formula below to implement the hashCode() of my class, say ClassA.
There are 6 String fields to be compared in the equals() and hence my hashCode() will include these 6 fields.
On using this formula, the calculated hash code is very large, sometimes it is negative, say -1342574843. I guess it is because the value is bigger than a int can contain. My question is: is there any harm about this? How come there is a negative sign? Thx.
public int hashCode(){
int result = 17;
result = 37*result + ((this.value != null) ? this.value.hashCode() : 0);
result = 37*result + ((this.code != null) ? this.code.hashCode() : 0);
return result;
}
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11154
    
  16

as i understand it, you are basically creating a bit pattern as your hash key. for some strings, the top bit gets set to 1. this makes it negative. it shouldn't hurt anything.
i think...


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
 
subject: Jason Bloch's hashCode formula
 
Similar Threads
component class not found exception
code generation of an effective hashCode
Need some help IndexOf method...pls
Creating a quality hashcode method
Detecting and rejecting duplicate grades using equals and hashCode