以下代码及注释来自java.util.HashTable
/**
* The hash table data.
*/privatetransient Entry<K,V>[] table;
以下代码及注释来自java.util.HashMap
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
以下代码及注释来自java.util.HashTable
// hash 不能超过Integer.MAX_VALUE 所以要取其最小的31个bitint hash = hash(key);
int index = (hash & 0x7FFFFFFF) % tab.length;
// 直接计算key.hashCode()privateinthash(Object k){
// hashSeed will be zero if alternative hashing is disabled.return hashSeed ^ k.hashCode();
}
以下代码及注释来自java.util.HashMap
int hash = hash(key);
int i = indexFor(hash, table.length);
// 在计算了key.hashCode()之后,做了一些位运算来减少哈希冲突finalinthash(Object k){
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// 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);
}
// 取模不再需要做除法staticintindexFor(int h, int length){
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";return h & (length-1);
}
以下代码及注释来自java.util.HashTable
/**
* A hashtable enumerator class. This class implements both the
* Enumeration and Iterator interfaces, but individual instances
* can be created with the Iterator methods disabled. This is necessary
* to avoid unintentionally increasing the capabilities granted a user
* by passing an Enumeration.
*/privateclassEnumerator<T> implementsEnumeration<T>, Iterator<T> {
Entry[] table = Hashtable.this.table;
int index = table.length;
Entry<K,V> entry = null;
Entry<K,V> lastReturned = null;
int type;
/**
* Indicates whether this Enumerator is serving as an Iterator
* or an Enumeration. (true -> Iterator).
*/boolean iterator;
/**
* The modCount value that the iterator believes that the backing
* Hashtable should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/protectedint expectedModCount = modCount;
Enumerator(int type, boolean iterator) {
this.type = type;
this.iterator = iterator;
}
//...
}
7. HashTable已经被淘汰了,不要在代码中再使用它。
以下描述来自于HashTable的类注释:
If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use java.util.concurrent.ConcurrentHashMap in place of Hashtable.