Question

I am little bit confused about HashSet internal working, as i know HashSet uses key(K) to find the right bucket and equals used to compare values but how HashSet works means how it generate hash Key ?

Was it helpful?

Solution

here it is

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);
}

it's actually in HashMap which HashSet uses internally

OTHER TIPS

Internally HashSet use HashMap,the hash key of the value is generated and used to save the element in HashTable.

To generate HashCode of the element the method HashCode() is called

Below method of HashMap to put element which is internally used by HashSet to add element :

 public V put(K paramK, V paramV)
      {
        if (paramK == null)
          return putForNullKey(paramV);
        int i = hash(paramK.hashCode());
-----------------------------^
        // More code
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top