javainthashcodeprimitive

Hashcode of an int


What is the hashcode of a primitive type, such as int?

for example, let's say num was an interger.

int hasCode = 0;

if (num != 0) {
  hasCode = hasCode + num.hashCode();
}

Solution

  • For the hashCode of an int the most natural choice is to use the int itself. A better question is what to use for the hashCode of a long since it doesn't fit into the int-sized hashcode. Generally, your best source for that—and all hashCode-related questions—would be Effective Java.

    Here's what Effective Java recommends (and the JDK uses) for the long type:

    (int) (value ^ (value >>> 32))