Difference between HashMap and HashTable

Difference between HashMap and HashTable

1. Hashtable is thread-safe, the method is Synchronized, suitable for use in a multi-threaded environment, and the efficiency is slightly lower; HashMap is not thread-safe, the method is not Synchronized, and the efficiency is slightly higher, suitable for use in a single-threaded environment, so in If you use it in multi-threaded situations, you need to manually synchronize the HashMap. (In the case of intense thread competition, the efficiency of HashTable is very low . Because when a thread accesses the synchronization method of HashTable, threads accessing other synchronization methods may enter a blocking or polling state. For example,
thread 1 uses put to add elements, thread 2 Not only cannot use the put method to add elements, but also cannot use the get method to obtain elements, so the more intense the competition, the lower the efficiency),

2. Both the key and value of HashMap can be null values, and the key and value of HashTable are not allowed to have Null values.

3 The default size of the array in HashMap is 16, and it must be a multiple of 2. The length of the expanded array is twice the length of the previous array. The default size of the array in HashTable is 11, and the length of the expanded array is 2 times +1 of the previous array length.

4 Hash values ​​are used differently.
HashMap recalculates the hash value and uses & instead of modulo:

int hash = hash(key.hashcode());
int i = indexFor(hash, table.length);
static int hash(Object x) {
int h = x.hashCode();
h += ~(h << 9);
h ^= (h >>> 14);
h += (h << 4);
h ^= (h >>> 10);
return h;
}

static int indexFor(int h, int length) {
return h & (length-1); //hashmap 的表长永远是 2^n。
}

HashTable uses the object's hashCode value directly:

int hash = key.hashCode(); //注意区分 2 者的 hash 值! !
int index = (hash & 0x7FFFFFFF) % tab.length;

5. Determine whether it contains a key
In HashMap, null can be used as a key, there is only one such key; there can be one or more keys corresponding to the value of null. When the get() method returns a null value, it either means that the key does not exist in the HashMap, or that the value corresponding to the key is null . Therefore, in HashMap, the get() method cannot be used to judge whether a key exists in the HashMap, but the containsKey() method should be used to judge. The key value of Hashtable cannot be null, so you can use the get() method to determine whether it contains a key.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325501567&siteId=291194637