Java
hashCode
data types
type conversion
programming tips

How should I map long to int in hashCode?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Java hashCode() must return an int, so a long field has to be reduced from 64 bits to 32 bits. The correct approach is not a plain cast. The standard approach is to mix the high and low 32-bit halves so the hash keeps information from the whole long.

Why Direct Casting Is Weak

A simple cast keeps only the lower 32 bits:

java
long value = 0x00000001_00000000L;
int weak = (int) value;
System.out.println(weak);

That discards the upper half completely. Different long values can collapse to the same int even when their high bits differ.

For example:

java
1long a = 0x00000001_00000000L;
2long b = 0x00000002_00000000L;
3
4System.out.println((int) a);
5System.out.println((int) b);

Both cast to 0, which is a poor hash contribution.

The Standard Formula

The usual manual formula is:

java
int mixed = (int) (value ^ (value >>> 32));

This xors the top 32 bits with the bottom 32 bits, so both halves influence the final result.

Java already provides this as:

java
int mixed = Long.hashCode(value);

That is the clearest answer in most modern Java code.

Using It in a Real hashCode()

java
1import java.util.Objects;
2
3public final class Account {
4    private final long id;
5    private final String owner;
6    private final int status;
7
8    public Account(long id, String owner, int status) {
9        this.id = id;
10        this.owner = owner;
11        this.status = status;
12    }
13
14    @Override
15    public boolean equals(Object o) {
16        if (this == o) return true;
17        if (!(o instanceof Account other)) return false;
18        return id == other.id
19                && status == other.status
20                && Objects.equals(owner, other.owner);
21    }
22
23    @Override
24    public int hashCode() {
25        int result = 17;
26        result = 31 * result + Long.hashCode(id);
27        result = 31 * result + Objects.hashCode(owner);
28        result = 31 * result + status;
29        return result;
30    }
31}

This is conventional, readable, and distribution-friendly enough for ordinary Java collections.

Objects.hash(...) Versus Manual Combination

You can also write:

java
1@Override
2public int hashCode() {
3    return java.util.Objects.hash(id, owner, status);
4}

That is perfectly acceptable for many classes. The manual version is more explicit and avoids some extra overhead in very hot code, but the key rule remains the same: do not reduce a long to an int with a plain cast unless you knowingly accept weaker hashing.

Why High and Low Bits Both Matter

Hash-based structures such as HashMap and HashSet depend on reasonable distribution. If your long IDs vary mostly in the upper bits, a cast loses the distinguishing information. Mixing high and low bits reduces avoidable collisions.

The point is not cryptographic randomness. The point is to represent the full field better in the 32-bit hashCode contract.

Keep equals() and hashCode() Consistent

The larger rule is that any field used in equals() should normally contribute to hashCode() too. If id is part of equality but not hashing, the object breaks the expectations of hash-based collections.

Also be careful with mutable fields. If a field contributing to the hash changes after insertion into a HashMap, later lookups can fail unexpectedly.

Common Pitfalls

Using (int) value directly is the classic mistake because it throws away the upper 32 bits.

Updating equals() fields without updating hashCode() leads to broken collection behavior even if the code still compiles.

Assuming Objects.hash(...) is always the best answer ignores performance-sensitive cases where manual combination is clearer and cheaper.

Treating hash mixing as if it were a cryptographic design problem overcomplicates a simple Java collection requirement.

Summary

  • 'hashCode() must return int, so a long field needs proper 64-bit to 32-bit mixing.'
  • The standard answer is Long.hashCode(value) or the equivalent xor formula.
  • A direct cast is weaker because it discards the upper half entirely.
  • Keep equals() and hashCode() aligned on the same logical fields.
  • Prefer standard, readable hash mixing unless you have measured a real need for something else.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.