hashmap
1. hash()
key.hashCode是返回的是地址值,如果key没重写hashCode时候,重写了调用的是自己的,hash方法将hashCode的高16位与低16位异或运算得到的值,这样能充分运用到高16位
发下key==null或者String s=""时候,他们的hash值都是0
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2. get(Object key)方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode(int hash, Object key)
- 判断表是否不为空,且表长度大于0,定位到的桶下标位置不为null的话, 不满足上面情况时候说明原来hashmap中没有该元素返回null,
- 满足的时候开始比较,先判断桶的第一个节点的hash方法是否和get的这个元素的hash是否相同,再直接**==比较**是否相等或者判断key不为空的话,调equals方法比较
- 不等的话,判断是否还有下一个节点,同时先判断这个桶结点首节点是否是树节点,是的话,调树的getTreeNode方法进行比较,通过root()方法先找到树的根节点,然后find方法通过hash二分的方法开始比较,
- 是链表的话就doWhile调链表的方法进行比较.
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) {
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;
}


3. put(K key, V value)方法
put 方法调的是putVal方法,先判断表示否为空,表大小是否为0,是的话就进行扩容,不是的话通过&运算定位到桶的位置,如果该位置为空就直接new一个节点放进去,有值的话,那么就先hash再 == 判断,再equals判断第一个节点是否是同一个key,满足条件就记录该结点用元素e记录,然后跳出判断,不满足就判断该桶位置元素是否是树节点,是的话就调用树节点的putTreeNode方法进行判断,不是的话就说明是链表,就遍历链表,通过hash == equasl方法去判断,同时如果发现链表节点数大于8那么就进行treeifyBin方法(treeifyBin时候如果发现表为空,或者表长小于64那么就进行扩容不进行树化),否之则先用双向链表把结点连接起来然后进行树化treeify。 最后会判断onIfAbsent如果为true且旧值不为null的时候不替换旧值,否则替换旧值.
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/***
*
* @param hash hash值
* @param key 指定的key
* @param value 指定参数value
* @param onlyIfAbsent 如果为true,即使指定参数key在map中已经存在,也不会替换value
* @param evict 如果为false,数组table在创建模式中
* @return 如果value被替换,则返回旧的value,否则返回null。当然,可能key对应的value就是null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//表为空的时候或者表长度为0的时候扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//通过&运算定位到桶的位置,如果该位置没有元素,直接new一个节点把该值放到该位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//有值的话,那么就先hash再 == 判断,再equals判断第一个节点是否是同一个key,那么就判断
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断是否是树结构,是的话在树结构中查找
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//否则是链表,开始链表方式遍历查找
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//里面已经有了8个,插入第九个时候开始扩容
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e!=null表示存在,是value间的替换,返回旧值就行
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//需要改的时候更换,如果onlyIfAbsent 为true且oldValue有值就不该
// 访问后回调
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
// 更新结构化修改信息
++modCount;//如果是找到key修改信息这个值不会加,因为不会运行到这里
//插入后++size再比较阈值,大于的话就扩容
if (++size > threshold)
resize();
// 插入后回调,为LinkedHashMap服务的
afterNodeInsertion(evict);
//原本里面没有元素那么就返回null
return null;
}
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
移除二分法,通过hash值进行二分,dir -1 左边 dir 1右边
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
final void treeifyBin(HashMap.Node<K,V>[] tab, int hash) {
int n, index; HashMap.Node<K,V> e;
//如果哈希表为空,或者小于转化树时候最小容量将进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();//扩容
// 如果符合转化为红黑树的条件,而且hash对应的桶不为null
else if ((e = tab[index = (n - 1) & hash]) != null) {
// 红黑树头结点 红黑树尾结点
HashMap.TreeNode<K,V> hd = null, tl = null;
do {
//替换链表node为树node,建立双向链表
HashMap.TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
//遍历链表插入每个节点到红黑树
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
4. 构造函数
空参构造器只是赋值加载因子为0.75
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
指定初始容量,调的还是两个参数的构造器,加载因子赋值0.75
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
容量小于0直接抛异常,如果容量大于2的30次方也就是1<<30,那么赋值为2的30次方,如果加载因子小于0或者是NaN数那么也抛出异常。正常情况赋予加载因子为参数传的,阈值为大于等于传的容量且是2的整数倍的最小值
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
可能不清楚NaN是什么,但是看下面解释和java判断NaN就理解了
NaN(Not a Number,非数)是计算机科学中数值数据类型的一类值,表示未定义或不可表示的值。常在浮点数运算中使用。首次引入NaN的是1985年的[IEEE 754](https://baike.baidu.com/item/IEEE 754/3869922)浮点数标准。
public static boolean isNaN(float v) { return (v != v); }
返回大于等于cag的最小值且是2的整数倍的值
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
5. resize() 扩容
- 判断旧容量是否空为空的话容量大小为0
- 如果原来表容量不空
- 如果容量还大于2的30次方时候不能扩容,返回旧数组,设置阈值为Integer.MAX_VALUE
- 如果容量扩容2倍后2小于的30次方,且旧容量大于64那么就直接阈值扩大2倍,否之往下走
- 如果表容量为空,旧阈值大于0的话,那么就可以把这个阈值赋值给新容量
- 如果表容量为空,旧阈值不大于0,那么就赋予默认64容量,48阈值
- 如果新的阈值为0,那么就用加载因子算出新的阈值.因为构造器构造时候第一次赋予加载因子为2的整数倍,是没有乘加载因子的值.
- 创建hash表,然后根据hash值&旧容量也就是判断新增的高位是否为1来定位元素的位置,是1的话他的位置将变为旧位置加旧容量,为0的话就不需要变,还在原来位置,同时通过头插法进行插入的.是树的话就调用树的分割方法split,是链表调的就按链表来操作
final HashMap.Node<K,V>[] resize() {
HashMap.Node<K,V>[] oldTab = table;
//算出没扩容前哈希表的大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold; //没扩容器那的阈值
int newCap, newThr = 0;
if (oldCap > 0) { //如果原来哈希表长度大于0
if (oldCap >= MAXIMUM_CAPACITY) { //容量大于1<<30次方时候
threshold = Integer.MAX_VALUE; //直接将阈值设置为整形的最大值 2的31次方-1
return oldTab; //无法扩容,返回原来的数组
}
//原来现在容量扩大两倍小于最大值,且原来容量大于初始值
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold 新的阈值扩大为原来的2倍
}
//如果旧容量<=0 且阈值(临界值)>0时候
else if (oldThr > 0) // initial capacity was placed in threshold
// 数组的新容量设置为老数组扩容的临界值
newCap = oldThr;
//如果旧容量 <= 0,且旧临界值 <= 0,新容量扩充为默认初始化容量,新临界值
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; //16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
}
//在当上面的条件判断中,只有oldThr > 0成立时,newThr == 0,只有这一步没有对newThr进行赋值
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
//&&左右都为true的时候才返回ft
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//将扩容后hashMap的临界值设置为newThr
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
table = newTab;
if (oldTab != null) {
//遍历旧哈希表的每个桶,将旧哈希表中的桶复制到新的哈希表中
for (int j = 0; j < oldCap; ++j) {
HashMap.Node<K,V> e;
//如果旧桶不为null,使用e记录旧桶
if ((e = oldTab[j]) != null) {
//将旧桶置为null
oldTab[j] = null;
//如果旧桶中只有一个node
if (e.next == null)
//将e也就是oldTab[j]放入newTab中e.hash & (newCap - 1)的位置
newTab[e.hash & (newCap - 1)] = e;
//如果旧桶中的结构为红黑树
else if (e instanceof HashMap.TreeNode)
//将树中的node分离
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果旧桶中的结构为链表,链表重排,jdk1.8做的一系列优化
else { // preserve order
HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
next = e.next;
//就是区分新增的那一位是否等于0如果是就是原索引,不是就是原索引加oldcap
if ((e.hash & oldCap) == 0) {
if (loTail == null) //尾是空的,说明还没有元素构建成链表,开始构建你第一个
loHead = e;
else
loTail.next = e;
loTail = e;
}
//等于1的时候
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//尾部不是空的时候,让 尾巴指向空
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead; //更新哈希表j位置为该链表(新增的1位为0的)
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead; //把j+原表长度位置更新为新建的链表
}
}
}
}
}
return newTab;
}
6. putAll(省略)
将参数map中的所有键值对映射插入到hashMap中,如果有碰撞,则覆盖value。
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
//新的表的最小容量为多少
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
//该值大于临界值
if (t > threshold)
//更新临界值为大于该t的最小的数 且是2的幂 这个和调用hashmap有参构造器中最后一句代码一样
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize(); //扩容
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
7.remove(Object key))
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;
//对应桶中有元素进入if
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
//node为移除的结点
HashMap.Node<K,V> node = null, e; K k; V v;
//第一个节点就是的要移除的时候
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//如果对应的桶中是以红黑树结构存在的
if (p instanceof HashMap.TreeNode)
//找到该结点
node = ((HashMap.TreeNode<K,V>)p).getTreeNode(hash, key);
else { //是以链表形式存在的
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null); //找到要移除的结点,没有的时候e==null跳出循环
}
}
//如果得到的node不为null且(matchValue为false||node.value和参数value匹配)
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof HashMap.TreeNode) //节点是树节点
//移除该界限
((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) //该结点是头结点 相等说明就是只有一个节点
tab[index] = node.next;
else
p.next = node.next; //或者让改p节点指向删除结点的下一个节点
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
//表为空 或者hash映射到桶为空 时候返回null
return null;
}
8.clear()
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
面试问题
1.7和1.8变化
https://juejin.cn/post/6844904097842200590
- 头插法(扩容出现死循环)变成了尾插法
https://juejin.cn/post/6844904084173144071
- 扩容后数据存储位置计算方式不同
- 扩容后插入变为扩容前插入
2. 是否允许空值
key和value允许为空,hash值为0
3. put操作
- 调putval,然后先判断是否需要初始化,然后判断hash所在桶位置是否为空,为空直接插入,不为空,判断key是否相同(hash == equals ),相同则覆盖其旧值,不同,则判断是否是树节点,不是的话则说明是链表,判断链表里面元素是否有相同的key,没有则插入. 然后再判断是否需要扩容
4. 为什么 HashMap 中 String、Integer 这样的包装类适合作为 key 键
- final类型 (保证了Hash值的不可更改性 计算准确性)
- 内部重写了equals和hashCode方法 (减少hash碰撞)
5. 红黑树
- 二叉搜索树/二叉排序树/二叉查找树
- 平衡二叉搜索树
- 红黑树
特点:
1.结点是红色或黑色。
2.根结点是黑色。
3.每个叶子结点都是黑色的空结点(NIL结点)。
4.每个红色结点的两个子结点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色结点)
5.从任一结点到其每个叶子的所有路径都包含相同数目的黑色结点。

1202

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



