标签:hashtable
HashTable源码--put方法和get方法:
// 将key-value对添加到HashTable中,如果已存在,则新值替旧值,并返回旧值
public synchronized V put(K key, V value) {
// Hashtable中不能插入value为null的元素!
if (value == null) {
throw new NullPointerException();
}
// 若该key对应的键值对已经存在,则用新的value取代旧的value;返回了旧的value后,退出!
Entry tab[] = table;
int hash = key.hashCode();
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;
}
}
// 若该key对应的键值对不存在,则将key-value对添加到table中
modCount++;
// 若Hashtable实际容量count大于或等于阀值时,扩容
if (count >= threshold) {
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// 将key-value对添加到table中
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
}
--------------------
// 返回key对应的value,没有的话返回null
public synchronized V get(Object key) {
Entry tab[] = table;
int hash = key.hashCode();
// 计算bucket的位置(即table的下标)
int index = (hash & 0x7FFFFFFF) % tab.length;
// 找到“key对应的Entry(链表)”,然后在链表中找出“哈希值”和“键值”与key都相等的元素
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;
}
另请参照文章: 【
HashMap源码分析】
标签:hashtable
原文地址:http://blog.csdn.net/wodewutai17quiet/article/details/46238873