-
首先向get()方法中传递一个key
-
在get()方法中调用hash(key),如果key!=null,返回该key的哈希值hash = key.hashCode()^ (h >>> 16),否则返回hash=0
-
在get()方法中调用getNode(hash,key)方法,获取该key的节点,并返回value
-
getNode()方法中首先要判断Hashtable是否为空且table长度大于0且该hash值对应的table元素不为空,条件成立则判断该节点的哈希值是否等于hash,依次遍历该链表或红黑树,查找key==node.key?返回查找到的节点的value
// JDK源码
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//判断hashtable是否为空,key对应的tab[ ]是否为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断第一个节点的hash,key是否相等
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//判断下一个节点是否为空
if ((e = first.next) != null) {
//判断是否是红黑树的节点,并遍历查找元素
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}