HashTable和HashMap
我們面試過程中 經(jīng)常會被問到HashTable和HashMap的區(qū)別 我們往往都是按照網(wǎng)上的那一套異同詩朗誦一下 但是不看一下源碼總是感覺心里沒底 所以來分析一下源碼
構(gòu)造方法
構(gòu)造方法兩參數(shù)分別為初始大小和加載因子 和HashMap沒什么區(qū)別
public Hashtable() {
this(11, 0.75f);
}
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
//HashtableEntry是鏈表格式
table = new HashtableEntry<?,?>[initialCapacity];
// Android-changed: Ignore loadFactor when calculating threshold from initialCapacity
// threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
threshold = (int)Math.min(initialCapacity, MAX_ARRAY_SIZE + 1);
}
我們可以看到 數(shù)據(jù)還是存放在鏈表數(shù)組中 和HashMap的數(shù)據(jù)結(jié)構(gòu)基本一致
put()
public synchronized V put(K key, V value) {//注意這里是同步方法
// Make sure the value is not null
if (value == null) {//不允許value為空
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
HashtableEntry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
HashtableEntry<K,V> entry = (HashtableEntry<K,V>)tab[index];
//匹配key相同的數(shù)
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
//key不存在與列表中 將key添加到鏈表的頭部
addEntry(hash, key, value, index);
return null;
}
我們可以看到這是一個同步方法 所以這就是我們背書的線程安全
get()
public synchronized V get(Object key) {
HashtableEntry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
//遍歷鏈表
for (HashtableEntry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
get操作也比較簡單 首先也是同步方法 就是根據(jù)key的hash值 獲取鏈表 然后遍歷鏈表找到key對應(yīng)的值 找不到就返回null
總結(jié)
簡單分析了一下HashTable的put和get方法 可以發(fā)現(xiàn)HashTable的數(shù)據(jù)結(jié)構(gòu)是數(shù)組+鏈表的方法 而且所有操作也是線程安全的 和HashMap的區(qū)別大致有
- HashMap是非線程安全 繼承AbstractMap HashTable是線程安全 繼承Directionary
- HashMap可以接受key和value為null值 而HashTable不可以
- HashTable在單線程過程中 要比HashMap慢 而在java5 提供了ConCurrentHashMap來替代HashTable