Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Objects.hash()

Computes a hash code from several values — for implementing hashCode().

Available since: Java 7

Syntax

static int hash(Object... values)

Parameters

ParameterTypeDescription
valuesObject...The fields used in equals().

Return value

intA hash code that depends on all values and their order.

Examples

Same values give the same hash:

void main() {
    IO.println(Objects.hash("Anna", 30) == Objects.hash("Anna", 30));
    IO.println(Objects.hash("Anna", 30) == Objects.hash(30, "Anna"));
    IO.println(Objects.hash((Object) null));
}

Output:

true
false
31

Notes

Pass the same fields that equals() compares — no more. null is allowed. For a single value Objects.hashCode(value) is simpler and returns 0 for null.

See also

  • Object.hashCode() — Returns the object's hash code — a number HashMap and HashSet use to find it quickly.
  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.

Related recipes

In the tutorial

  • Equality and hash codes — Comparing objects in Java — == and equals, the equals and hashCode contract, Objects.equals and Objects.hash, records and the HashSet mistake.

Thanks for reading!

Donate to the site — we work hard for you.