Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Object.hashCode — the hash-code contract

Object.hashCode returns an int used by hash tables. Objects equal according to equals must have matching codes; the reverse does not hold.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public int hashCode()

Object.hashCode() is a public instance method returning an int, used by hash tables such as HashMap. The default implementation attempts to distinguish objects but does not guarantee uniqueness.

If a.equals(b), then a.hashCode() == b.hashCode() must hold. Collisions are allowed: matching codes do not prove equality. The result must remain stable within one execution while data used by equals stays unchanged; it may differ between executions.

Overriding equals generally requires overriding hashCode to preserve this contract. The example defines both methods using the immutable id field: separate Key(7) instances are equal and return code 7.

Examples

public class Main {
    static final class Key {
        private final int id;

        Key(int id) {
            this.id = id;
        }

        @Override
        public boolean equals(Object other) {
            return other instanceof Key && id == ((Key) other).id;
        }

        @Override
        public int hashCode() {
            return id;
        }
    }

    public static void main(String[] args) {
        Key a = new Key(7);
        Key b = new Key(7);
        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println(a.hashCode());
        System.out.println(a.hashCode() == b.hashCode());
    }
}

Result

false
true
7
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources