8

Sometimes I need to implement an obj's hashCode() method by combining the hashCodes of its several instance members. For example, if the combinational obj has members a, b, and c, I often see ppl implement it as


int hashCode(){
   return 31 * 31 * a.hashCode() + 31 * b.hashCode() + c.hashCode();
}

Where does this magic number 31 come from? Is it the length of 4-bytes or just a prime number?

Is there any other preferred/standard way of implementing hashCode()?

dolaameng
  • 1,397
  • 2
  • 17
  • 24
  • Similar (but not necessarily duplicate): http://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode – Mark Peters Oct 06 '10 at 03:24
  • The prime 31 is used in String.hashCode() This makes a good prime as there are not many different possible characters, however I tend to use larger primes. A good site for "interesting" primes is http://primes.utm.edu/curios/ – Peter Lawrey Oct 06 '10 at 05:57

6 Answers6

8

See Effective Java's recipe. It's just the best source, hands down.

The use of a prime number is just to try to get a reasonably good distribution without knowing the domain. It will take a while to overflow to the same value. The value 31 is pretty arbitrary if I recall correctly.

According to Bloch (he uses 17 as an initial value and 37 as the constant multiplier):

A nonzero initial value is used (...) so the hash value will be affected by initial fields whose hash value (...) is zero. If zero was used as the initial value (...) the overall hash value would be unaffected by any such initial fields, which could increase collisions. The value 17 is arbitrary.
...
The multiplier 37 was chosen because it is an odd prime. If it was even and the multiplication overflowed, information would be lost because multiplication by two is equivalent to shifting. The advantages of using a prime number are less clear, but it is traditional to use primes for this purpose.

KiKMak
  • 828
  • 7
  • 27
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • CW since I`m just shamelessly quoting Bloch. – Mark Peters Oct 06 '10 at 03:15
  • 4
    In the second edition of Effective Java, Josh Bloch uses 31 rather than 37. He explains that choice: "A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: `31 * i == (i << 5) - i`. Modern VMs do this sort of optimization automatically." – ColinD Oct 06 '10 at 03:46
6

One good option is Guava's Objects.hashCode method. It takes any number of arguments and creates a hashcode based on them:

@Override public int hashCode() {
  return Objects.hashCode(a, b, c);
}
ColinD
  • 108,630
  • 30
  • 201
  • 202
2

Use HashCodeBuilder from Commons Lang:

public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

See the API for ways to do it without using reflection. You can tell it which fields to include, or which to ignore.

See also EqualsBuilder, for overriding an equals method.

wmorgan
  • 178
  • 5
1

Generate it using your IDE.

Michael Barker
  • 14,153
  • 4
  • 48
  • 55
0

I believe the following is a good practice for simple scenarios: If your class contain any readonly members, they would be good candidates for generating the object's hashcode. If your class, however, contains only the mutating members, you could create a readonly int field that gets the value based on the non-null values passed to the constructor.

Mahorad
  • 1,258
  • 1
  • 15
  • 22
0

basically, your hash code should consist of the key parameter of your POJO. One Example is below.

public int hashCode() {
    int hash = 0;
    if (getRollId() != null) {
        hash += getRollId().hashCode();
    }
    if (getName() != null) {
        hash += getName().hashCode();
    }
    return hash == 0 ? System.identityHashCode(this) : hash;
}

In the above example, the roll id and name are the key parameter of that POJO.

It is a good practice if you add only those parameter into the hashCode method that you add in Eqauls method of the same POJO.

M.J.
  • 16,266
  • 28
  • 75
  • 97