How a HashSet creates a hashkey for an object or value

I am a little confused about the internal workings of the HashSet, since I know that the HashSet uses the key (K) to find the right bucket and is used equal to compare values, but how does the HashSet work, how does it generate the hash key?

+3
source share
2 answers

here

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

this is actually in the HashMap that the HashSet uses internally

+3
source

The internal HashSet uses a HashMap, a value hash key is generated and used to store the item in a HashTable.

To generate a hashcode element, the method HashCode()is called

Below the HashMap method, place the element that HashSet internally uses to add the element:

 public V put(K paramK, V paramV)
      {
        if (paramK == null)
          return putForNullKey(paramV);
        int i = hash(paramK.hashCode());
-----------------------------^
        // More code
      }
+1
source

All Articles