Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can put all the Integers in Java HashSet and use its hashCode.</p> <p>On the other hand, java.util.Set does specify the following in documents:</p> <blockquote> <p>Returns the hash code value for this set. The hash code of a set is defined to be the <strong>sum of the hash codes of the elements in the set</strong>, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode().</p> </blockquote> <p>And Integer.hashCode() is then</p> <blockquote> <p>a hash code value for this object, <strong>equal to the primitive int value</strong> represented by this Integer object.</p> </blockquote> <p>Thus the hashCode for set of integers <code>i1, i2, ... i_n</code> in Java standard library is <code>i1 + i2 + ... + i_n</code>.</p> <p>In case that the numbers are rather small, you can also multiply each element by a some suitably sized prime number. Knuth used 2654435761 which is too big for an java int, but you can take its 2-complement, -1640531527. Thus take C = -1640531527, and then your code is <code>C*i1 + C*i2 + ... C*i_n</code>.</p> <pre><code>private static final int C = -1640531527; public static int calculateHash(int[] set) { int code = 0; for (int e: set) { code += C * e; } return code; } </code></pre> <p>However there is 1 obvious flaw in the thinking. To make any use of the hashCode, you need to be able to prove that 2 sets are indeed equal, thus in any case the easiest way to prove is to sort the elements. Of course if there are substantially less than millions of sets then there are not that many collisions either.</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