Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are mixing many different concrete types in the same map's key set, you can still use <code>Objects.hashCode()</code> and minimize collisions by xoring the output with a different value per concrete type.</p> <pre><code>class Class1 { public int hashCode() { return Object.hashCode(...) ^ 0x12b7eff8; } } class Class2 { public int hashCode() { return Object.hashCode(...) ^ 0xe800792b; } } </code></pre> <p>By xoring with a value that is randomly chosen, but stable per-concrete class, you eliminate the chance of collisions that might occur solely because the arguments to <code>Object.hashCode</code> are equivalent.</p> <blockquote> <blockquote> <p>Warning: When a single object is supplied, the returned hash code does not equal the hash code of that object.</p> </blockquote> <p>Is this why the javadoc warns about only supplying a single object to this method? From the javadoc,</p> </blockquote> <p>No. This warning is not about the chance of collisions between instances of different concrete classes that have the same members. It is instead warning about false negatives in hashcode matches due to an assumption that the hash of a single value is the same as that of the <code>singleValue.hashCode()</code>.</p> <p>For example, look at the assumption made below in the <em>incorrect</em> fast track code that tries to avoid an equality check by using cached hash codes:</p> <pre><code>class Name { int cachedHashCode; ... } class Person { int cachedHashCode; // 0 if not computed private final Name name; public boolean hasName(Name n) { return ((cachedHashCode != 0 &amp;&amp; n.cachedHashCode != 0) &amp;&amp; cachedHashCode == n.cachedHashCode) || n.equals(name); } public int hashCode() { if (cachedHashCode == 0) { cachedHashCode = Object.hashCode(name); } return cachedHashCode; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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