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 ?

有帮助吗?

解决方案

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

其他提示

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
      }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top