CKTIS / Java
Hash a primitive long with Long.hashCode(long)
Compute a 32-bit hash code from a primitive `long` without boxing it, and see why different inputs can produce the same result.
Version: Java SE 21
Syntax
public static int hashCode(long value)Long.hashCode(long) is a static method on java.lang.Long, available since Java 8. Call Long.hashCode(value) with a 64-bit primitive long to get a signed int without boxing. The no-argument instance method Long.hashCode() returns the same code for the same value but needs a Long object. Passing a Long variable that holds null to the static method throws NullPointerException during unboxing.
The result is equivalent to (int) (value ^ (value >>> 32)). The zero-fill right shift >>> moves the upper 32 bits into the lower half. The operator ^ performs bitwise exclusive OR (XOR), and the cast to int keeps the low 32 bits of the result. In contrast, (int) value simply discards the upper bits.
Use this method to compute a long field's contribution to an object's hash code. Equal values always give the same code, but unequal values can also give the same code: that's a collision. Don't use the code as proof of equality, a unique ID, or a cryptographic hash.
Examples
public class Main {
public static void main(String[] args) {
long lowBit = 1L;
long highBit = 1L << 32;
Long boxed = Long.valueOf(highBit);
System.out.println(Long.hashCode(lowBit));
System.out.println(Long.hashCode(highBit));
System.out.println((int) highBit);
System.out.println(Long.hashCode(highBit) == boxed.hashCode());
}
}Result
1 1 0 true
`1L` and `1L << 32` are different values, but both hash to `1`. Casting the second value to `int` gives `0`, and the final `true` shows that the static and instance methods agree.
Related lessons
- Java · Lesson 4 · Intermediate · Version: 2
Sources
- Java SE 21 API — Long.hashCode(long)
- Java SE 21 API — Long.hashCode()
- Java SE 21 API — Object.hashCode()
- Java SE 21 Language Specification §15.19 — Shift Operators
- Java SE 21 Language Specification §15.22.1 — Integer Bitwise Operators
- Java SE 21 Language Specification §5.1.3 — Narrowing Primitive Conversion
- Java SE 21 Language Specification §5.1.8 — Unboxing Conversion