Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Objects.hash: compute a hash code from several values

`Objects.hash` combines values into one `int` hash code. Learn how `Object...` handles mixed arguments, when boxing occurs, and how to stay consistent with `equals`.

Version: Java SE 21

Syntax

import java.util.Objects;

// Static method declared in java.util.Objects:
public static int hash(Object... values)

// Example call:
int hash = Objects.hash(42, "A", "B");

Objects.hash is a static method in java.util.Objects. It returns an int hash code for an ordered sequence of values. In Objects.hash(42, "A", "B"), the Object... parameter (varargs) lets you pass the values separately: Java packs them into an Object[]. The primitive int value 42 is boxed to Integer, while the two String values are already references.

The result is the same as Arrays.hashCode(Object[]). Starting at 1, each step multiplies the running result by 31 and adds the element's hash code, or 0 for a null element. Changing the order can change the result. For a single non-array object, Objects.hash(x) hashes a one-element sequence. Use Objects.hashCode(x) if you want the object's own hash code, or 0 for null.

If you pass an Object[] directly, its elements form the sequence. If an array is itself an element of the sequence, its contents are not hashed recursively. Objects.hash((Object[]) null) returns 0 because the whole array is absent, whereas Objects.hash((Object) null) returns 31 because there is one null element.

When implementing hashCode(), choose values so that objects considered equal by equals always produce the same result. A straightforward approach is to use the same fields and account for how equals compares them. The reverse does not hold: unequal objects can share a hash code (a collision). Do not use this code as a persistent identifier or as a cryptographic hash.

Examples

import java.util.Objects;

public class Main {
    record Key(int id, String first, String second) {
        @Override
        public int hashCode() {
            return Objects.hash(id, first, second);
        }
    }

    public static void main(String[] args) {
        Key left = new Key(42, "A", "B");
        Key right = new Key(42, "A", "B");

        System.out.println(left.equals(right));
        System.out.println(left.hashCode() == right.hashCode());
        System.out.println(left.hashCode());
    }
}

Result

true
true
72234

The generated `equals` method compares the three components of `Key`. The custom `hashCode()` passes those same components in a fixed order, so both keys are equal and have the hash code `72234`.

Related lessons

  • Java · Lesson 28 · Intermediate · Version: 2

Sources