简体   繁体   中英

Does Java HashTable abide by the load factor (we specify) when we use a custom hash function?

Java allows us to specify the size and required load factor of the hash table we wish to create. If we use a custom HashCode method to generate keys on our own then the load factor must become dependent on the efficiency/goodness of our HashCode. How do I know that the load factor requirements i specified initially are still being met?

Below the load factor i want is 0.67.

Hashtable<Long, String[]> ht = new Hashtable<>(100, 0.67f);

However if I say the following

public int hashCode(int n){
 int a = n%72;
 return a;}

Then will the load factor of 0.67 still be preserved even though my hashcode function is quite poor?

As per your question, load factor of 0.67 still be preserved even if hashcode function is poor. Load factor is used to decide when to increase the size of the internal structure to accommodate new data set. In case of poor hashcode function, you may encounter many collisions.

Other experts can throw more light on this and help me to improve my answer.

Here's the link to the Java8 implementation of HashTable.
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/Hashtable.java . Its a great resource to understand what would happen if you overrodecertain default methods.

Coming to your question: The hashCode method has not effect on the load factor. The loadfactor is used every single time you put an entry into the table to check if the collection needs a rehash. Capacity of the hashtable by default is 11 and the threshold is capacity * loadFactor. If the current count of entries in the table exceeds this value, a rehash will be executed with a collection twice the size of your original Table.
The hashCode method doesnt impact this process , however as pointed in the earlier answer, it controls the collisions and also is directly responsible for the performance of your Hashtable. A bad hash function is as good as storing all the data in a few LinkedLists and iteratively searching in the corresponding list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM