HashTable与HashMap的区别

来源:互联网 发布:淘宝没有上下架时间 编辑:程序博客网 时间:2024/06/11 16:07

1.Hashtable继承自Dictionary类,而HashMap继承自AbstractMap类。但二者都实现了Map接口。

 public class Hashtable<K,V>     extends Dictionary<K,V>     implements Map<K,V>, Cloneable, java.io.Serializable 

public class HashMap<K,V>    extends AbstractMap<K,V>     implements Map<K,V>, Cloneable, Serializable 


2、Hashtable中的方法是同步的(),而HashMap中的方法在默认情况下不是同步的。即是说,在多线程应用程序中,不用专门的操作就安全地可以使用Hashtable了;而对于HashMap,则需要额外的同步机制。但HashMap的同步问题可通过Collections的一个静态方法得到解决:

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
这个方法返回一个同步的Map,也就是说返回的Map是线程安全的。需要注意的是,对返回的map进行迭代时,必须手动在返回的map上进行同步,否则将会导致不确定的行为:
Map m = Collections.synchronizedMap(new HashMap());       ...   Set s = m.keySet();  // Needn't be in synchronized block       ...   synchronized(m) {  // Synchronizing on m, not s!       Iterator i = s.iterator(); // Must be in synchronized block       while (i.hasNext())           foo(i.next());   }

3.在HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示HashMap中没有该键,也可以表示该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键,而应该用containsKey()方法来判断。Hashtable的键值不能为null,否则put的时候:java.lang.NullPointerException 。


4.HashTable使用Enumeration,HashMap使用Iterator。以上只是表面的不同,它们的实现也有很大的不同。


5.HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。
6.哈希值的使用不同,HashTable直接使用对象的hashCode,代码是这样的:

int hash = key.hashCode();int index = (hash & 0x7FFFFFFF) % tab.length;

而HashMap重新计算hash值,而且用与代替求模,比如HashMap的put方法:

public V put(K key, V value) {         if (key == null)             return putForNullKey(value);         int hash = hash(key.hashCode());         int i = indexFor(hash, table.length);         for (Entry<K,V> 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;     }static int hash(int h) {         // This function ensures that hashCodes that differ only by         // constant multiples at each bit position have a bounded         // number of collisions (approximately 8 at default load factor).         h ^= (h >>> 20) ^ (h >>> 12);         return h ^ (h >>> 7) ^ (h >>> 4);     }   static int indexFor(int h, int length) {         return h & (length-1);     }


0 0
原创粉丝点击