Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Only check hashCode in equals() of immutable object
    text
    copied!<p>I have an immutable object, for example a node in the Cartesian space. The class is immutable, so I cache the <code>hashCode</code> for very fast hashing. </p> <pre><code>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) &amp;&amp; Objects.equal(this.y, other.y) &amp;&amp; Objects.equal(this.z, other.z); } @Override public int hashCode() { return this.hashCode; } </code></pre> <p>Since the <code>hashCode</code> is unique and dependent on all fields of the class AND the class is Immutable, would it be correct to only check <code>Node</code> equality based on the <code>hashCode</code>?</p> <pre><code>@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; } </code></pre> <p>This passes all Unit Tests I have written about the properties of <code>equals()</code> and <code>hashCode()</code> and their interaction, but perhaps there is something I am missing?</p> <p>Note: <code>Objects.hashCode()</code> and <code>Objects.equal()</code> are Guava classes helpful for the respective methods.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload