2

I have overwritten the hashcode-method for my class (with one instance variable named "id").

public int hashCode()
{
  final int prime = 31;
  int result = 1;

  result = prime * result + ((id == null) ? 0 : id.hashCode());
  return result;
}

What exactly happens in the last line? There should be two different cases:

Case 1: id == null , which means that result should be equal to 31.

Case 2: id != null , which means that result should be equal to 31 + id.hashCode();

I do not understand the two cases (or i am not even sure if they are correct). And what is the point of the prime number anyway? Why should we assign the null reference to 31?

Ubuntix
  • 324
  • 4
  • 15
  • http://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode – Eugene Mar 14 '14 at 10:13
  • http://books.google.co.in/books?id=ka2VUBqHiWkC&pg=PA45&lpg=PA45&dq=hashcode+in+java+joshua&source=bl&ots=yYLjPnpZU_&sig=lDXdsiTqmnu_TU3PO81E3S7rQ1E&hl=en&sa=X&ei=k9YiU9raJsPrrQfVz4DgAw&ved=0CHEQ6AEwCA#v=onepage&q=hashcode%20in%20java%20joshua&f=false Best place from where you can learn about hashcode and why 31 only. – Gaurav Gupta Mar 14 '14 at 10:16
  • http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier – Christophe Roussy Mar 14 '14 at 10:18

1 Answers1

1

what is the point of the prime number anyway? 31 is a ODD-PRIME number and to choose an Odd number prevents multiplication over-flow and prime is a traditional approach.

I think this part can be understand in more detailed manner from here

Why should we assign the null reference to 31

((id == null) ? 0 : id.hashCode()) Here we are checking if id has a non-null value or not. If there is some non-null value then it must be having some hashcode and we are adding that hashcode in our object's hashcode. So this way your hashcode for two object will differ if id for those two object differs.

Community
  • 1
  • 1
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72
  • but why do i need 31? i've read everything but i don't get it. Couldn't i just use id.hashCode(); why do i multiply with 31? If the hashcode of id is unique it would be still unique if we mulitply it with a number, wouldn't it? – Ubuntix Mar 14 '14 at 12:47
  • Yes, if you remove multiplication by 31 then also hashcode will be unique. but for efficiency we need to multiply it by odd prime. – Gaurav Gupta Mar 14 '14 at 13:05
  • so why is it more efficient? – Ubuntix Mar 14 '14 at 13:12
  • This is what i have directly picked from the source u suggested ub comment "The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. "... – Gaurav Gupta Mar 14 '14 at 13:34