1.7的hashMap
学习hashMap具备的基础:位运算,集成,接口的实现,数据结构,数组+链表(红黑树)
https://www.bilibili.com/video/BV1H3411q7s7?p=8
拓展:左移相当于乘以2,右移除以2。
https://www.yuque.com/shier-tcmwp/notes/vb9f90
1.8的hashMap
资料来源:https://www.bilibili.com/video/BV1yX4y1w7ng?share_source=copy_web
public class HashMap<K, V> extends AbstractMap<K, V>
implements Map<K, V>, Cloneable, Serializable { // 1、实现了两个Map接口,重复--》多余
// 3、属性部分
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
transient Node<K,V>[] table; // 底层数组
// 2、 调用空构造器
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // loadFactor = 0.75
}
// 4、调用有参构造器
public HashMap(int initialCapacity) { //10
this(initialCapacity, DEFAULT_LOAD_FACTOR); // this(10,0.75)
}
//5、跳到HashMap中
public HashMap(int initialCapacity, float loadFactor) { // 10,0.75
// 6、提高健壮性处理
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);
// 7、loadFactor = 0.75
this.loadFactor = loadFactor;
// 8、调用tableSizeFor方法,传入10
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
* 9、tableSizeFor---》确定主数组的长度 ---》返回的是最接近参数的2的n次幂 ----》10=》16 3=》4 6=》8
*/
static final int tableSizeFor(int cap) { // 10
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;
}
// 10、调用put方法
public V put(K key, V value) {\
// 11、调用hash方法
return putVal(hash(key), key, value, false, true);
}
// 12、hash方法,返回值就是hash码
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 13、putVal方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 14、调用resize方法,该方法
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
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);
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;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
// 15、调用resize方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 16、resize方法从开始到这里都是确定table的大小。重要的地方是就是这里,table:底层的数组长度在这里确定了,为一个xxx长度的Node类型的数组
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
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;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
}
经典面试题:
1、装填因子,装载因子,加载因子为什么要设置为0.75。
装填因子设置为1,空间利用率得到大大的提高,很容易发生碰撞,产生链表-》查询效率低
装填因子设置为0.5,空间利用率太低了,碰撞几率也低,产生链表低-》查询效率高。
所以取了一个折中的:0.75
2、主数组的长度为什么必须为2的n次方。
原因1:h & (length - 1)等效 h % length 操作,等效的前提是:length必须是2的整数倍。
原因2:防止哈希冲突,位置冲突。
- 验证是整数倍:
length:8
hash :3 00000011
length-1 00000111
——————————————————与运算,相同为1,不同为0
00000011 —-》3 位置
hash :2 00000010
length-1 00000111
——————————————————
00000010 ——-》2位置
- 验证不是整数倍:
length:9
hash :3 00000011
length-1 00001000
—————————————
00000000 ——》0位置
hash :2 00000010
length-1 00001000
—————————————————
00000000 ——》0位置
3、头插法为什么有循环问题