public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { //HashTable不可以存Null值 throw new NullPointerException(); }
// Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = hash(key); int index = (hash & 0x7FFFFFFF) % tab.length; //计算桶位 for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { V old = e.value; e.value = value; return old; } }
modCount++; if (count >= threshold) { //默认空间不足容量的75%开始扩容 // Rehash the table if the threshold is exceeded rehash(); tab = table; hash = hash(key); index = (hash & 0x7FFFFFFF) % tab.length; }
// Creates the new entry. Entry<K,V> e = tab[index]; tab[index] = new Entry<>(hash, key, value, e); count++; return null; }
table = newMap; //两层for循环.外层循环桶位,内层循环链表元素,对每个元素进行重新计算在新数组中的桶位 for (int i = oldCapacity ; i-- > 0 ;) { for (Entry<K,V> old = oldMap[i] ; old != null ; ) { Entry<K,V> e = old; old = old.next;
if (rehash) { e.hash = hash(e.key); // } int index = (e.hash & 0x7FFFFFFF) % newCapacity;//计算新的桶位 e.next = newMap[index]; newMap[index] = e; } } }
int index = (e.hash & 0x7FFFFFFF) % newCapacity 由于Hash Table的桶位基于最大容量,每次扩容都要重新计算一遍桶位
4.HashTable的get方法
public synchronized V get(Object key) { Entry tab[] = table; int hash = hash(key); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return e.value; } } return null; }