HashMap Hashtable區別

 


分類: java基礎 2009-02-24 17:26  21310人閱讀  評論(3)  收藏  舉報

http://blog.csdn.net/java2000_net/archive/2008/06/05/2512510.aspx java

 

 咱們先看2個類的定義 this

[java]  view plain copy
  1. public class Hashtable  
  2.     extends Dictionary  
  3.     implements Map, Cloneable, java.io.Serializable  
[java]  view plain copy
  1. public class HashMap  
  2.     extends AbstractMap  
  3.     implements Map, Cloneable, Serializable  

可見Hashtable 繼承自 Dictiionary 而 HashMap繼承自AbstractMap spa

 

Hashtable的put方法以下 .net

[java]  view plain copy
  1. public synchronized V put(K key, V value) {  //###### 注意這裏1  
  2.   // Make sure the value is not null  
  3.   if (value == null) { //###### 注意這裏 2  
  4.     throw new NullPointerException();  
  5.   }  
  6.   // Makes sure the key is not already in the hashtable.  
  7.   Entry tab[] = table;  
  8.   int hash = key.hashCode(); //###### 注意這裏 3  
  9.   int index = (hash & 0x7FFFFFFF) % tab.length;  
  10.   for (Entry e = tab[index]; e != null; e = e.next) {  
  11.     if ((e.hash == hash) && e.key.equals(key)) {  
  12.       V old = e.value;  
  13.       e.value = value;  
  14.       return old;  
  15.     }  
  16.   }  
  17.   modCount++;  
  18.   if (count >= threshold) {  
  19.     // Rehash the table if the threshold is exceeded  
  20.     rehash();  
  21.     tab = table;  
  22.     index = (hash & 0x7FFFFFFF) % tab.length;  
  23.   }  
  24.   // Creates the new entry.  
  25.   Entry e = tab[index];  
  26.   tab[index] = new Entry(hash, key, value, e);  
  27.   count++;  
  28.   return null;  
  29. }  

 

注意1 方法是同步的
注意2 方法不容許value==null
注意3 方法調用了key的hashCode方法,若是key==null,會拋出空指針異常 HashMap的put方法以下 指針

[java]  view plain copy
  1. public V put(K key, V value) { //###### 注意這裏 1  
  2.   if (key == null)  //###### 注意這裏 2  
  3.     return putForNullKey(value);  
  4.   int hash = hash(key.hashCode());  
  5.   int i = indexFor(hash, table.length);  
  6.   for (Entry e = table[i]; e != null; e = e.next) {  
  7.     Object k;  
  8.     if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
  9.       V oldValue = e.value;  
  10.       e.value = value;  
  11.       e.recordAccess(this);  
  12.       return oldValue;  
  13.     }  
  14.   }  
  15.   modCount++;  
  16.   addEntry(hash, key, value, i);  //###### 注意這裏   
  17.   return null;  
  18. }  

 

注意1 方法是非同步的
注意2 方法容許key==null
注意3 方法並無對value進行任何調用,因此容許爲null blog

補充: 
Hashtable 有一個 contains方法,容易引發誤會,因此在HashMap裏面已經去掉了
固然,2個類都用containsKey和containsValue方法。 繼承

 

                           HashMap                Hashtable get

父類                  AbstractMap          Dictiionary 同步

是否同步            否                            是 hash

k,v能否null     是                            否

相關文章
相關標籤/搜索