HashTable,不容許鍵值爲null,還一個就是put方法使用sychronized方法進行線程同步,單線程無需同步,多線程可用concurren包的類型。 如編程思想裏面說的做爲工具類,封閉性作的很差沒有一個方法變量是final的,做爲java1.0/1.1時代的容器逐漸被HashMap取代。一樣Vector也有一樣的問題,做爲普通集合類,添加數據的方法也是作了同步,效率受極大影響。java
HashTable源碼中的put,鍵和值都不容許爲null /** * Maps the specified <code>key</code> to the specified * <code>value</code> in this hashtable. Neither the key nor the * value can be <code>null</code>. <p> * * The value can be retrieved by calling the <code>get</code> method * with a key that is equal to the original key. * * @param key the hashtable key * @param value the value * @return the previous value of the specified key in this hashtable, * or <code>null</code> if it did not have one * @exception NullPointerException if the key or value is * <code>null</code> * @see Object#equals(Object) * @see #get(Object) */ public synchronized V put(K key, V value) { // Make sure the value is not null,值爲null報空指針 if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry<?,?> tab[] = table; int hash = key.hashCode();//key爲null,沒法計算hashcode也會報空指針 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; }