Never been to DZone Snippets before?

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

Compact hashcode method (See related posts)

   1  
   2  class Foo {
   3      private String string;
   4      private Date date;
   5      private i;
   6      
   7      [...]
   8  
   9      public int hashCode() {
  10          int result;
  11          result = (string != null ? string.hashCode() : 0);
  12          result = 29 * result + (date != null ? date.hashCode() : 0);
  13          result = 31 * result + (i != null ? i : 0);
  14          [...]
  15          return result;
  16      }


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

Comments on this post

DRMacIver posts on Mar 31, 2007 at 14:12
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5551 code snippets

Related Posts