Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Integer.hashCode: primitive value vs. Integer object

Use `Integer.hashCode(id)` for a primitive `int` and `boxed.hashCode()` for an `Integer` object. Both return the same numeric value as the hash code.

Version: Java SE 21

Syntax

java.lang.Integer (Java SE 21)
public static int hashCode(int value)  // Integer.hashCode(id), where id is an int
public int hashCode()                  // boxed.hashCode(), where boxed is an Integer

In java.lang.Integer, the name Integer.hashCode refers to two methods. The static method Integer.hashCode(int) has been available since Java 8. When id is an int, Integer.hashCode(id) returns exactly id without requiring boxing. The result can be negative.

The no-argument instance method Integer.hashCode() overrides Object.hashCode(). Calling boxed.hashCode() returns the int value stored in boxed. Calling it on a null reference throws NullPointerException. Passing a null variable of type Integer to the static method also throws that exception, but during unboxing to int.

If your class compares an int id field in equals, use Integer.hashCode(id) as that field's contribution to the hash code. Equal objects must have equal hash codes, but matching hash codes do not prove equality. For Integer, equals requires the other object to be an Integer holding the same value.

This method does not hide an ID: it returns the ID unchanged. It is not a cryptographic hash function.

Examples

public class IntegerHashCodeDemo {
    public static void main(String[] args) {
        int id = -42;
        Integer boxed = Integer.valueOf(id);

        System.out.println(Integer.hashCode(id));
        System.out.println(boxed.hashCode());
    }
}

Result

-42
-42

The first line comes from the static call on an `int`; the second comes from the instance call on an `Integer`. Both print `-42` because the hash code equals the value.

Related lessons

  • Java · Lesson 5 · Advanced · Version: 2
  • Java · Lesson 17 · Advanced · Version: 2
  • Java · Lesson 5 · Intermediate · Version: 2

Sources