DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Compact Hashcode Method

04.12.2005
| 2446 views |
  • submit to reddit
        
class Foo {
    private String string;
    private Date date;
    private i;
    
    [...]

    public int hashCode() {
        int result;
        result = (string != null ? string.hashCode() : 0);
        result = 29 * result + (date != null ? date.hashCode() : 0);
        result = 31 * result + (i != null ? i : 0);
        [...]
        return result;
    }

Consider using larger prime numbers  if the number of properties is large.    

Comments

Snippets Manager replied on Wed, 2007/02/14 - 2:44pm

Are the prime numbers really useful? That looks like it has the potential to screw things up quite spectacularly. You want to guarantee that your hash codes are randomly distributed mod n for any n. If e.g. I'm storing a bunch of Foo values which have null string and date, if my hash table happens to have a multiple of 31 buckets I've suddenly got linear time lookups on values! I tend to combine hash codes with ^. Arithmetic operations produce odd peaks if your hash codes aren't large enough to cause integer overflow when combined.