What's the difference between HashMap and Hashtable?
This article is to share with you about the difference between HashMap and Hashtable. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Hashtable is thread safe, while HashMap is not thread safe.
Synchronized keyword is added to the implementation of Hashtable to ensure thread synchronization.
HashMap can use null as key, while Hashtable does not allow null as key
HashMap is the implementation of Map interface, and HashTable implements Map interface and Dictionary abstract class.
The initial capacity of HashMap is 16, the initial capacity of Hashtable is 11, and the fill factor of both is 0.75 by default.
The current capacity of HashMap is doubled when it is expanded: capacity*2
When Hashtable is expanded, its capacity doubles + 1, that is, capacity*2+1.
The two methods of calculating hash are different.
Static int hash (int h) {/ / 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);} static int indexFor (int h, int length) {return h & (length-1);}
Int hash = key.hashCode (); int index = (hash & 0x7FFFFFFF)% tab.length
The calculation of hash by Hashtable directly uses the hashcode of key to directly model the length of the table array.
HashMap calculates hash to hash the hashcode of key twice to get a better hash value, and then takes the length of the table array.
The underlying implementation of HashMap and Hashtable is array + linked list structure.
Thank you for reading! This is the end of the article on "what's the difference between HashMap and Hashtable". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!