天天看點

HashTable源碼分析

/**

The hash table data.

*/

//存放鍵值對的數組

private transient Entry<?,?>[] table;

The total number of entries in the hash table.

//大小

private transient int count;

The table is rehashed when its size exceeds this threshold. (The

value of this field is (int)(capacity * loadFactor).)

@serial

//閥值

private int threshold;

The load factor for the hashtable.

//負載因子

private float loadFactor;

//預設初始容量為11,負載因子0.75

public Hashtable() {

this(11, 0.75f);

}

//1.8版本沒有修改,沒有維護紅黑樹結構

public synchronized V put(K key, V value) {

// Make sure the value is not null

if (value == null) {

throw new NullPointerException();

Removes the key (and its corresponding value) from this

hashtable. This method does nothing if the key is not in the hashtable.

@param key the key that needs to be removed

@return the value to which the key had been mapped in this hashtable,

or <code>null</code> if the key did not have a mapping

@throws NullPointerException if the key is <code>null</code>

public synchronized V remove(Object key) {

Entry<?,?> tab[] = table;

int hash = key.hashCode();

int index = (hash & 0x7FFFFFFF) % tab.length;br/>@SuppressWarnings("unchecked")

Entry<K,V> e = (Entry<K,V>)tab[index];

for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {

if ((e.hash == hash) && e.key.equals(key)) {

modCount++;

if (prev != null) {

prev.next = e.next;

} else {

tab[index] = e.next;

count--;

V oldValue = e.value;

e.value = null;

return oldValue;

return null;

繼續閱讀