1、Hashtable是Dictionary的子类,
1 public class Hashtable2 extends Dictionary 3 implements Map , Cloneable, java.io.Serializable
HashMap:
1 public class HashMap2 extends AbstractMap 3 implements Map , Cloneable, Serializable
HashMap和Hashtable都是Map接口的一个实现类;
2、Hashtable中的方法是同步的(),而HashMap中的方法在默认情况下不是同步的。即是说,在多线程应用程序中,不用专门的操作就安全地可以使用Hashtable了;而对于HashMap,则需要额外的同步机制。但HashMap的同步问题可通过Collections的一个静态方法得到解决:
1 public staticMap synchronizedMap(Map m)
1 Map m = Collections.synchronizedMap(new HashMap());2 ...3 Set s = m.keySet(); // Needn't be in synchronized block4 ...5 synchronized(m) { // Synchronizing on m, not s!6 Iterator i = s.iterator(); // Must be in synchronized block7 while (i.hasNext())8 foo(i.next());9 }
1 int hash = key.hashCode();2 int index = (hash & 0x7FFFFFFF) % tab.length;
而HashMap重新计算hash值,而且用与代替求模,比如HashMap的put方法:
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 (Entrye = 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 16 modCount++;17 addEntry(hash, key, value, i);18 return null;19 }
1 static int hash(int h) {2 // This function ensures that hashCodes that differ only by3 // constant multiples at each bit position have a bounded4 // number of collisions (approximately 8 at default load factor).5 h ^= (h >>> 20) ^ (h >>> 12);6 return h ^ (h >>> 7) ^ (h >>> 4);7 }
1 static int indexFor(int h, int length) {2 return h & (length-1);3 }