从源码分析HashMap和Hashtable的区别
1. 线程同步,Hashtable线程安全,HashMap线程不安全。
原因:
hashtable加了锁。
hashtable:
public synchronized V put(K key, V value)
hashMap:
public V put(K key, V value)
2. 效率问题,Hashtable效率低,HashMap效率高。
原因:
加了锁自然效率低啦。
3.Hashtable的方法是同步的,HashMap未经同步,所以在多线程场合要手动同步HashMap这个区别就像Vector和 ArrayList一样。
4.Hashtable不允许 null 值(key 和 value 都不可以),HashMap允许 null 值(key和value都可以)。
原因:
hashtable:
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = hash(key);
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = hash(key);
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
return null;
}
hashMap:
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
5.两者的遍历方式大同小异,Hashtable仅仅比HashMap多一个elements方法。 Hashtable 和 HashMap 都能通过values()方法返回一个 Collection ,然后进行遍历处理。 两者也都可以通过 entrySet() 方法返回一个 Set , 然后进行遍历处理。
6.HashTable使用Enumeration,HashMap使用Iterator。
7.哈希值的使用不同,Hashtable直接使用对象的hashCode。而HashMap重新计算hash值,而且用于代替求模。
8.Hashtable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2 的指数,负载因子(默认值是0.75)。
9.HashTable基于Dictionary类,而HashMap基于AbstractMap类。
public class Hashtable extends Dictionary implements Map, Cloneable, java.io.Serializable
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable