底层实现
数组+链表+红黑树
一些重要的变量
//默认初始容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//容量最大值
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化的阈值,当桶中链表节点数大于8时,将链表转换为红黑树
static final int TREEIFY_THRESHOLD = 8;
//红黑树退化为链表的阈值,当桶中红黑树节点数小于6时,将红黑树转换为链表
static final int UNTREEIFY_THRESHOLD = 6;
//最小的树化容量,进行树化的时候,还有一次判断,只有键值对数量大于64时才会发生转换,
//这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表而导致不必要的转化
static final int MIN_TREEIFY_CAPACITY = 64;
get操作:get(K)
1.判断表是否为空或者待查找的桶不为空
2.首先检查待查找的桶的第一个元素是否是要找的元素,如果是直接返回
3.桶内红黑树,则调用getTreeNode()查找红黑树
4.桶内是链表,遍历链表寻找节点
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;
//表不为空&&表长大于0&&待查找的桶不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//首先检查桶中的第一个节点,如果相等,则直接返回
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;
}