HashMap小记
HashMap小记
HashMap线程不安全,ConcurrentHashMap线程安全
1.7HashMap
数组+链表
数组查询快,插入慢;链表插入删除快,查询慢
先了解一下里面定义的一些变量
static final int DEFAULT_INITIAL_CAPACITY = 16;//默认初始容量大小
static final int MAXIMUM_CAPACITY = 1073741824;//最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75F;//加载因子
static final HashMap.Entry<?, ?>[] EMPTY_TABLE = new HashMap.Entry[0];//存储的对象
transient HashMap.Entry<K, V>[] table;//数组
transient int size;//大小
int threshold;//阀值
final float loadFactor;//负荷系数
transient int modCount;//计数
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = 2147483647;//哈希阀值
transient int hashSeed;
private transient Set<java.util.Map.Entry<K, V>> entrySet;
private static final long serialVersionUID = 362498820763181265L;
put(k,v)插入方式:头插法
public V put(K var1, V var2) {
if (this.table == EMPTY_TABLE) {
this.inflateTable(this.threshold);
}
if (var1 == null) {//如果k为空,直接放到:this.table[0]
return this.putForNullKey(var2);
} else {
int var3 = this.hash(var1);//生成hashcode
int var4 = indexFor(var3, this.table.length);//找到插入位置
//直接放到头部,如果头部有值了,值往下移var5 = var5.next
for(HashMap.Entry var5 = this.table[var4]; var5 != null; var5 = var5.next) {
Object var6;
if (var5.hash == var3 && ((var6 = var5.key) == var1 || var1.equals(var6))) {
Object var7 = var5.value;
var5.value = var2;
var5.recordAccess(this);
return var7;
}
}
++this.modCount;
this.addEntry(var3, var1, var2, var4);
return null;
}
}
private V putForNullKey(V var1) {
for(HashMap.Entry var2 = this.table[0]; var2 != null; var2 = var2.next) {
if (var2.key == null) {
Object var3 = var2.value;
var2.value = var1;
var2.recordAccess(this);
return var3;
}
}
++this.modCount;
this.addEntry(0, (Object)null, var1, 0);
return null;
}
扩容:1.7先扩容,再添加
为什么要扩容?
不扩容,链表会非常长,遍历效率会慢
void addEntry(int var1, K var2, V var3, int var4) {
//如果size大小大于或等于临界值(阀值),添加的不是空,就扩容
if (this.size >= this.threshold && null != this.table[var4]) {
//两倍扩容
this.resize(2 * this.table.length);
var1 = null != var2 ? this.hash(var2) : 0;
var4 = indexFor(var1, this.table.length);
}
//添加
this.createEntry(var1, var2, var3, var4);
}
void createEntry(int var1, K var2, V var3, int var4) {
HashMap.Entry var5 = this.table[var4];
this.table[var4] = new HashMap.Entry(var1, var2, var3, var5);
++this.size;
}
注:可能会出现死循环
1.8HashMap
数组+链表+红黑树
为什么使用红黑树,什么时候使用红黑树?
- 红黑树的插入与查询的效率最平衡
- 当链表长度大于等于TREEIFY_THRESHOLD(树化阀值:8)时,树化
- 初始TREEIFY_THRESHOLD为8;因为根据泊松分步,链表长度大于8的概率已经很低了
- 红黑树链化:当进行移除操作后,达到UNTREEIFY_THRESHOLD(链化阀值:6)时,链化
- 如果一小于8就链化,效率比较低,切树化和链化操作会很频繁
/**默认初始大小*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**最大容量 */
static final int MAXIMUM_CAPACITY = 1 << 30;
/**树化阀值 */
static final int TREEIFY_THRESHOLD = 8;
/**链化阀值 */
static final int UNTREEIFY_THRESHOLD = 6;
/* 最小负载容量,当数组达到64,且满足树化阀值时才将链表树化*/
static final int MIN_TREEIFY_CAPACITY = 64;
put(K,V):尾插法
看一段源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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)
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大于阀值-1;树化,但并不是真正的树化,里面还有判断
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;
}
从源码可以得知:它在遍历时,遍历结束后,顺便把put的的值放入链尾
扩容:先插入再扩容
扩容源码
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];
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;
//对原链表进行分组,等于0还在原来的数组下标,等于1,原下标+原容量
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:为什么hashMap每次扩容为之前的两倍(即以2的幂次方扩容)
看一段源码
final int hash(Object var1) {
int var2 = this.hashSeed;
if (0 != var2 && var1 instanceof String) {
return Hashing.stringHash32((String)var1);
} else {
var2 ^= var1.hashCode();
var2 ^= var2 >>> 20 ^ var2 >>> 12;
return var2 ^ var2 >>> 7 ^ var2 >>> 4;
}
}
static int indexFor(int var0, int var1) {
return var0 & var1 - 1;
}
indexFor方法中使用生成的hashcode与数组大小-1;进行与&比较
这里面已经把他们转换为了2进制;
16: 0001 0000
var0: 1011 0101
16-1: 0000 1111
&: 0000 0101
这保证了,插入数据的下标一定在数组容量中,而这也是它需要每次以2的幂次方扩容的原因
为什么hashcode需要进行右移和异或处理
var2 ^= var1.hashCode();
var2 ^= var2 >>> 20 ^ var2 >>> 12;
return var2 ^ var2 >>> 7 ^ var2 >>> 4;
这可以减少哈希碰撞,减少某个链表过长的情况,使get(K)不至于太慢
加载因子有什么用
加载因子也叫作扩容因子,用来判断什么时候进行扩容,假设加载因子为0.75,HashMap的初始容量为16,当HashMap中有16 * 0.75 = 12个容量时,HashMap就会进行扩容。
如果加载因子越大,扩容发生的频率就会比较低,占用空间比较小,但是发生hash冲突的几率会提升,对元素操作时间会增加,运行效率降低;
如果加载因子太小,那么表中的数据将过于稀疏(很多空间还没用,就开始扩容了),对空间造成严重浪费;
而且因为容量默认为2的次方,当加载因子为0.75时,容量和加载因子的乘积为整数。
所以系统默认加载因子取了0.5 -1 之间的0.75
本文地址:https://blog.csdn.net/qq_41510551/article/details/109271108
上一篇: 雷电5接口曝光:速度提升至80Gbps
下一篇: 杭电oj 2734 java实现