源码:
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果根据hash定位到数组位置的第一个元素就是要查找的元素,则直接返回。此时为O(1)
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);
}
}
//没找到则返回null
return null;
}
总结:
- 在理想状态下,及未发生任何hash碰撞,数组中的每一个链表都只有一个节点,那么get方法可以通过hash直接定位到目标元素在数组中的位置,时间复杂度为O(1)。
- 若发生hash碰撞,则可能需要进行遍历寻找,n个元素的情况下,链表时间复杂度为O(n)、红黑树为O(logn)