1、get() 方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value; //实际调用的是 getNode(int hash, Object key) 方法
}
2、getNode() 方法
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final HashMap.Node<K,V> getNode(int hash, Object key) {
//定义变量
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> first, e; int n; K k;
//查看数据需要满足一下条件
//1)数组不为空
//2)数组长度>0
//3)通过hash计算出该元素在数组中存放位置的索引,而且该索引处数据不为空null
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) {
//如果第1个的元素是红黑树类型的节点
if (first instanceof HashMap.TreeNode)
//那我们需要调用红黑树的方法查找节点
return ((HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);
//如果不是,则该为链表,需要遍历查找
do {
//循环判断下一个节点的hash和key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
//更新e为下一个
} while ((e = e.next) != null);
}
}
//没找到返回Null
return null;
3、getTreeNode() 方法
/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
//root()获取根节点
//find遍历树结构,查找对象
return ((parent != null) ? root() : this).find(h, k, null);
}
4、find() 方法
/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
//获取当前对象
TreeNode<K,V> p = this;
//循环树结构
do {
int ph, dir; K pk;
//获取当前节点的左子节点,右子节点
TreeNode<K,V> pl = p.left, pr = p.right, q;
//根据hash值判断,p=左子节点,或右子节点
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
//p的key与之key对比,如果相同,则返回当前对象
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
//如果左子节点为空,则p=右子节点
else if (pl == null)
p = pr;
//如果右子节点为空,则p=左子节点
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
//嵌套查询,如果找到,则返回该对象
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
//循环对象,直到找到,或者循环结束
} while (p != null);
return null;
}
博客主要介绍了多种方法,但未明确方法的具体内容和所属领域。
1302

被折叠的 条评论
为什么被折叠?



