Java: Only check hashCode in equals() of immutable object

equals, guava, hashcode, immutability, java

Solution

Nope; that won't work.

You have 232 possible hashcodes and 2192 possible values.

Problem

I have an immutable object, for example a node in the Cartesian space. The class is immutable, so I cache the `hashCode` for very fast hashing. ``` private final int hashCode; private final double x, y, z; public Node(final double x, final double y, final double z) { this.x = x; this.y = y; this.z = z; this.hashCode = Objects.hashCode(this.x, this.y, this.z); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Node)) { return false; } final Node other = (Node) obj; return Objects.equal(this.x, other.x) && Objects.equal(this.y, other.y) && Objects.equal(this.z, other.z); } @Override public int hashCode() { return this.hashCode; } ``` Since the `hashCode` is unique and dependent on all fields of the class AND the class is Immutable, would it be correct to only check `Node` equality based on the `hashCode`? ``` @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Node)) { return false; } final Node other = (Node) obj; return this.hashCode == other.hashCode; } ``` This passes all Unit Tests I have written about the properties of `equals()` and `hashCode()` and their interaction, but perhaps there is something I am missing? Note: `Objects.hashCode()` and `Objects.equal()` are Guava classes helpful for the respective methods.

Original source

Related problems