http://blog.csdn.net/java2000_net/archive/2008/06/05/2512510.aspx java
咱們先看2個類的定義 this
- public class Hashtable
- extends Dictionary
- implements Map, Cloneable, java.io.Serializable
- public class HashMap
- extends AbstractMap
- implements Map, Cloneable, Serializable
可見Hashtable 繼承自 Dictiionary 而 HashMap繼承自AbstractMap spa
Hashtable的put方法以下 .net
- public synchronized V put(K key, V value) { //###### 注意這裏1
- // Make sure the value is not null
- if (value == null) { //###### 注意這裏 2
- throw new NullPointerException();
- }
- // Makes sure the key is not already in the hashtable.
- Entry tab[] = table;
- int hash = key.hashCode(); //###### 注意這裏 3
- int index = (hash & 0x7FFFFFFF) % tab.length;
- for (Entry 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 e = tab[index];
- tab[index] = new Entry(hash, key, value, e);
- count++;
- return null;
- }
注意1 方法是同步的
注意2 方法不容許value==null
注意3 方法調用了key的hashCode方法,若是key==null,會拋出空指針異常 HashMap的put方法以下 指針
- public V put(K key, V value) { //###### 注意這裏 1
- if (key == null) //###### 注意這裏 2
- return putForNullKey(value);
- int hash = hash(key.hashCode());
- int i = indexFor(hash, table.length);
- for (Entry 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;
- }
注意1 方法是非同步的
注意2 方法容許key==null
注意3 方法並無對value進行任何調用,因此容許爲null blog
補充:
Hashtable 有一個 contains方法,容易引發誤會,因此在HashMap裏面已經去掉了
固然,2個類都用containsKey和containsValue方法。 繼承
HashMap Hashtable get
父類 AbstractMap Dictiionary 同步
是否同步 否 是 hash
k,v能否null 是 否