0Pricing
Java Academy · Lesson

Implementing hashCode

Write correct hash functions.

Implementing hashCode is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Goals of a Good hashCode

A good hashCode() should:

  • Return the same value for equal objects (the contract).
  • Spread unequal objects across many different values.
  • Be cheap to compute.

A poor hashCode that returns a constant still satisfies the contract but turns the map into a slow linked list.

public class Main {
    public static void main(String[] args) {
        // Legal but terrible: every object collides
        System.out.println("constant hashCode is legal but kills performance");
    }
}

Objects.hash for the Common Case

The simplest correct approach is Objects.hash(field1, field2, ...).

It handles nulls and combines fields with a standard algorithm. Use the same fields you compare in equals.

import java.util.Objects;

public class Main {
    static class User {
        final String name; final int age;
        User(String name, int age) { this.name = name; this.age = age; }
        @Override public int hashCode() { return Objects.hash(name, age); }
    }
    public static void main(String[] args) {
        User a = new User("Ada", 36);
        User b = new User("Ada", 36);
        System.out.println(a.hashCode() == b.hashCode());
    }
}

The Classic 31 Multiplier

For a hand-written hash, the standard pattern multiplies a running result by 31 and adds each field's hash.

31 is an odd prime, and 31 * x is the same as (x << 5) - x, so the JVM can optimize it.

public class Main {
    static class User {
        final String name; final int age;
        User(String name, int age) { this.name = name; this.age = age; }
        @Override public int hashCode() {
            int result = 17;
            result = 31 * result + (name == null ? 0 : name.hashCode());
            result = 31 * result + age;
            return result;
        }
    }
    public static void main(String[] args) {
        System.out.println(new User("Ada", 36).hashCode());
    }
}

Hashing Primitives

Each primitive type has a recommended way to hash:

  • int: use the value itself.
  • long: (int)(value ^ (value >>> 32)).
  • boolean: 1 or 0.
  • double: Double.hashCode(value).
public class Main {
    public static void main(String[] args) {
        long id = 4_000_000_000L;
        int longHash = (int) (id ^ (id >>> 32));
        System.out.println("long hash: " + longHash);
        System.out.println("double hash: " + Double.hashCode(3.14));
        System.out.println("bool hash: " + Boolean.hashCode(true));
    }
}

Hashing Arrays

Do not call hashCode() directly on an array; it uses identity, not contents.

Use Arrays.hashCode(arr) for a flat array, or Arrays.deepHashCode(arr) for nested arrays.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println("identity equal: " + (a.hashCode() == b.hashCode()));
        System.out.println("content equal: " + (Arrays.hashCode(a) == Arrays.hashCode(b)));
    }
}

Keep equals and hashCode in Sync

The fields used in hashCode() must be a subset of the fields used in equals() (ideally exactly the same).

If equals compares more fields than hashCode, two equal objects still share a hash. That is allowed. But if hashCode uses a field equals ignores, you break the contract.

import java.util.Objects;

public class Main {
    static class Coord {
        final int x, y;
        Coord(int x, int y) { this.x = x; this.y = y; }
        @Override public boolean equals(Object o) {
            return o instanceof Coord c && c.x == x && c.y == y;
        }
        @Override public int hashCode() { return Objects.hash(x, y); }
    }
    public static void main(String[] args) {
        Coord a = new Coord(3, 4), b = new Coord(3, 4);
        System.out.println(a.equals(b) && a.hashCode() == b.hashCode());
    }
}

Caching the Hash

For immutable objects with expensive hashing, you can cache the result in a field.

String does exactly this internally. Only do it when the object is truly immutable, so the cached value never goes stale.

import java.util.Objects;

public class Main {
    static final class Key {
        final String a, b;
        private int hash; // 0 until computed
        Key(String a, String b) { this.a = a; this.b = b; }
        @Override public int hashCode() {
            int h = hash;
            if (h == 0) { h = Objects.hash(a, b); hash = h; }
            return h;
        }
    }
    public static void main(String[] args) {
        Key k = new Key("x", "y");
        System.out.println(k.hashCode());
        System.out.println(k.hashCode());
    }
}

Distribution Matters

A well-distributed hashCode spreads keys evenly across buckets. Let's count distinct hash codes for a batch of objects.

The more distinct values, the fewer collisions and the faster the map.

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Main {
    record Pair(int a, int b) {}
    public static void main(String[] args) {
        Set<Integer> hashes = new HashSet<>();
        for (int i = 0; i < 100; i++) {
            hashes.add(Objects.hash(i, i * 7));
        }
        System.out.println("distinct hashes: " + hashes.size());
    }
}

A Bad Distribution Example

Summing fields without multiplying produces collisions: (1,2) and (2,1) both hash to 3.

The 31 multiplier breaks this symmetry because order then matters.

public class Main {
    static int badHash(int a, int b) { return a + b; }
    static int goodHash(int a, int b) { return 31 * a + b; }
    public static void main(String[] args) {
        System.out.println("bad (1,2): " + badHash(1, 2) + ", (2,1): " + badHash(2, 1));
        System.out.println("good (1,2): " + goodHash(1, 2) + ", (2,1): " + goodHash(2, 1));
    }
}

Prefer Records for Value Types

For pure data carriers, a record generates a correct, well-distributed hashCode automatically.

Only hand-write hashCode when you need custom semantics or you cannot use a record.

public class Main {
    record Money(long cents, String currency) {}
    public static void main(String[] args) {
        Money a = new Money(1099, "USD");
        Money b = new Money(1099, "USD");
        System.out.println(a.equals(b));
        System.out.println(a.hashCode() == b.hashCode());
    }
}

Putting It Together

A complete value class: immutable fields, equals and hashCode from the same fields, and a clean toString.

import java.util.Objects;

public class Main {
    static final class Version {
        final int major, minor, patch;
        Version(int major, int minor, int patch) {
            this.major = major; this.minor = minor; this.patch = patch;
        }
        @Override public boolean equals(Object o) {
            return o instanceof Version v && v.major == major && v.minor == minor && v.patch == patch;
        }
        @Override public int hashCode() { return Objects.hash(major, minor, patch); }
        @Override public String toString() { return major + "." + minor + "." + patch; }
    }
    public static void main(String[] args) {
        Version v = new Version(2, 1, 0);
        System.out.println(v + " hash=" + v.hashCode());
    }
}

Quick Check

Test your hashCode skills.

Recap

You learned to implement hashCode correctly:

  • Use Objects.hash(...) for the common case.
  • The 31 multiplier pattern for hand-written hashing.
  • Hash arrays with Arrays.hashCode, not the default.
  • Keep hashCode fields in sync with equals, and prefer records.

Next, see how Java 8+ treeifies overloaded buckets.

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        System.out.println("hashCode recap done: " + Objects.hash("done"));
    }
}

Frequently asked questions

Is the “Implementing hashCode” lesson free?

Yes — the full text of “Implementing hashCode” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Implementing hashCode”?

Write correct hash functions. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Implementing hashCode” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. How HashMap Works
  2. The equals/hashCode Contract
  3. Implementing hashCode
  4. Treeification and Performance
← Back to Java Academy