I am wondering if we implement our own hashmap that doesn’t use power-of-two length hash tables (initial capacity and whenever we re-size), then in that case can we just use the object’s hashcode and mod the total size directly instead of use a hash function to hash the object’s hashcode ?
for example
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
// int hash = hash(key.hashCode()); original way
//can we just use the key's hashcode if our table length is not power-of-two ?
int hash = key.hashCode();
int i = indexFor(hash, table.length);
...
...
}
Presuming we’re talking about OpenJDK 7, the additional
hashis used to stimulate avalanching; it is a mixing function. It is used because the mapping function from a hash to a bucket, since were using a power of 2 for the capacity, is a mere bitwise&(sincea % bis equivalent toa & (b - 1)iffbis a power of 2); this means that the lower bits are the only important ones, so by applying this mixing step it can help protect against poorer hashes.If you want to use sizes that aren’t powers of 2, the above may not be needed.
Actually changing the mapping from hashes to buckets (which normally relies on the capacity being a power of 2) will require you to you to look at
indexFor:You could use
(h & 0x7fffffff) % lengthhere.