Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Objects.hash: a hash code from two fields

Combine two fields into an `int` hash code, see why Java autoboxes an `int` to `Integer`, and learn how `Objects.hash` differs from `Objects.hashCode`.

Version: Java SE 21

Syntax

import java.util.Objects;

// Java SE 21 — method declaration in java.util.Objects:
// public static int hash(Object... values)
int hash = Objects.hash(label, number); // label: String, number: int

In Java SE 21, the static method Objects.hash(Object... values) in java.util.Objects returns an int hash code for an ordered sequence of values. In Objects.hash(label, number), Java autoboxes the int field number to Integer and passes both values in an Object[].

The result follows Arrays.hashCode(Object[]): for a non-null array, start at h = 1 and apply h = 31 * h + (e == null ? 0 : e.hashCode()) for each element e. Order can affect the result. Objects.hash() returns 1, Objects.hash((Object) null) returns 31, and Objects.hash((Object[]) null) returns 0.

With one element, Objects.hash(x) still mixes the element's hash code with the initial value. Objects.hashCode(x) returns x.hashCode() directly, or 0 if x is null. An existing Object[] passed as the sole argument supplies the varargs array itself; cast it to Object to make it one element, whose contents are not hashed recursively.

When implementing hashCode(), combine fields in a way that matches how equals compares them. Equal objects must have equal hash codes, but unequal objects can collide. Don't use the result as a persistent ID or a cryptographic hash: the general hashCode() contract does not guarantee the same result across runs.

Examples

import java.util.Objects;

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

    public static void main(String[] args) {
        Key first = new Key("A", 7);
        Key second = new Key("A", 7);
        System.out.println(first.equals(second));
        System.out.println(first.hashCode() == second.hashCode());
        System.out.println(first.hashCode());
        System.out.println(Objects.hash(7));
        System.out.println(Objects.hashCode(7));
    }
}

Result

true
true
2983
38
7

The generated `equals` for `Key` compares both record components. The first two lines (`true`) show that the objects are equal and that their hash codes match. `2983` combines the hashes of `"A"` and `7`; `38` and `7` contrast hashing a one-element sequence with getting the element's own hash code.

Related lessons

  • Java · Lesson 18 · Advanced · Version: 2

Sources