Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top