在concurrentHashMap出来之前,hashtable一直是作为线程安全的map使用。
hashtable默认的初始大小是:11.
1.Hashtable中的put方法。
1.1 不同于HashMap,Hashtable不允许出现空的key.
1.2 不同于HashMap,下标计算方式
HashMap : h & (length-1)
Hashtable: (hash & 0x7FFFFFFF) % tab.length
2 Hashtable中的rehash方法:
Hashtable的增长方式是按照原有长度的2倍再加上1的方式进行增长的,不同于hashMap,hashMap是按照原有长度的2倍。
hashtable默认的初始大小是:11.
1.Hashtable中的put方法。
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 = key.hashCode();
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;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
}
1.1 不同于HashMap,Hashtable不允许出现空的key.
1.2 不同于HashMap,下标计算方式
HashMap : h & (length-1)
Hashtable: (hash & 0x7FFFFFFF) % tab.length
2 Hashtable中的rehash方法:
protected void rehash() {
int oldCapacity = table.length;
Entry[] oldMap = table;
int newCapacity = oldCapacity * 2 + 1;
Entry[] newMap = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
Hashtable的增长方式是按照原有长度的2倍再加上1的方式进行增长的,不同于hashMap,hashMap是按照原有长度的2倍。