Sobes.tech
Middle+

How to make your class immutable for use as a HashMap key?

sobes.tech AI

Answer from AI

To make a class immutable and safe to use as a key in HashMap, you should:

  • Make all fields final and private.
  • Do not provide setters.
  • Initialize all fields through the constructor.
  • If fields are mutable objects, create copies when assigning and returning them (to protect against external modifications).
  • Override equals() and hashCode() methods correctly, based on the fields.

Example:

public final class ImmutableKey {
    private final String id;
    private final int number;

    public ImmutableKey(String id, int number) {
        this.id = id;
        this.number = number;
    }

    public String getId() {
        return id;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ImmutableKey)) return false;
        ImmutableKey that = (ImmutableKey) o;
        return number == that.number && id.equals(that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, number);
    }
}

This class guarantees that after creation, the object will not change, and its hash code will remain constant, which is critical for keys in HashMap.