Hashtable和HashMap的区别

来源:互联网 发布:淘宝上靠谱的韩代 编辑:程序博客网 时间:2024/06/08 10:14

1、两者继承的直接父类不同:Hashtable继承自Dictiionary,HashMap继承自AbstractMap,这一区别可以通过两者的源码明显地看到:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class HashMap<K,V>  
  2.     extends AbstractMap<K,V>  
  3.     implements Map<K,V>, Cloneable, Serializable  
  4.   
  5. public class Hashtable<K,V>  
  6.     extends Dictionary<K,V>  
  7.     implements Map<K,V>, Cloneable, java.io.Serializable  

2、

Hashtable的put方法如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public synchronized V put(K key, V value) {  
  2.   // Make sure the value is not null   
  3.   if (value == null) {   
  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();   
  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.   
  18.   modCount++;   
  19.   if (count >= threshold) {   
  20.     // Rehash the table if the threshold is exceeded   
  21.     rehash();   
  22.     tab = table;   
  23.     index = (hash & 0x7FFFFFFF) % tab.length;   
  24.   }   
  25.   
  26.   // Creates the new entry.   
  27.   Entry e = tab[index];   
  28.   tab[index] = new Entry(hash, key, value, e);   
  29.   count++;   
  30.   return null;   
  31. }  
HashMap的put方法如下:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public V put(K key, V value) {   
  2.   if (key == null)  
  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. }   

        通过比对Hashtable与HashMap的put方法,我们很容易得出这样的结论:

        a、Hashtable的put方法是同步的,线程安全的;HashMap的put方法不是同步的,非线程安全的:由此可见在多线程情况下应该使用Hashtable中的put方法,反之应该使用HashMap中的put方法;由此也可以得出这样的结论Hashtable的put方法效率低于HashMap的put方法;

        b、在向Hashtable中put数据时,key与value均不能为null,而在向HashMap中put数据时,key与value都可以为空;

0 0
原创粉丝点击