ConcurrentHashmap HashMap和Hashtable都是key-value存儲結構,但他們有一個不同點是 ConcurrentHashmap、Hashtable不支持key或者value為null,而HashMap是支持的。為什么會有這個區別?在設計上的目的是什么?
ConcurrentHashmap和Hashtable都是支持並發的,這樣會有一個問題,當你通過get(k)獲取對應的value時,如果獲取到的是null時,你無法判斷,它是put(k,v)的時候value為null,還是這個key從來沒有做過映射。HashMap是非並發的,可以通過contains(key)來做這個判斷。而支持並發的Map在調用m.contains(key)和m.get(key),m可能已經不同了。
HashMap.class:
// 此處計算key的hash值時,會判斷是否為null,如果是,則返回0,即key為null的鍵值對 // 的hash為0。因此一個hashmap對象只會存儲一個key為null的鍵值對,因為它們的hash值都相同。 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } // 將鍵值對放入table中時,不會校驗value是否為null。因此一個hashmap對象可以存儲 // 多個value為null的鍵值對 public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
Hashtable.class:
public synchronized V put(K key, V value) { // 確保value不為空。這句代碼過濾掉了所有value為null的鍵值對。因此Hashtable不能 // 存儲value為null的鍵值對 if (value == null) { throw new NullPointerException(); } // 確保key在table數組中尚未存在。 Entry<?,?> tab[] = table; int hash = key.hashCode(); //在此處計算key的hash值,如果此處key為null,則直接拋出空指針異常。 int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; }