数据结构Map之HashMap
程序员文章站
2024-02-20 19:40:58
...
HashMap
key无序,唯一
value 无序,不唯一
线程不安全,效率高
允许key或值为null
底层
transient Node<K,V>[] table;
// 数组
transient Node<K,V>[] table;
// 链表
static class Node<K,V> implements Map.Entry<K,V>{
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
扩容
初始大小16,扩容因子0.75
扩容 2的N次方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
HashTable
线程安全,效率低
不允许key或值为null
初始化为11 扩容为2倍+1
1.7知识点
默认初始化容量 16
加载因子 0.75
第一次put时进行初始化
put 操作
设置值,计算hash
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
计算位置
static int indexFor(int h, int length) {
return h & (length-1);
}
public V put(K key, V value) {
//判断当前Hashmap(底层是Entry数组)是否存值(是否为空数组)
//如果为空,则初始化
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//判断key是否为空
if (key == null)
return putForNullKey(value);//hashmap允许key为空
//计算当前key的哈希值
int hash = hash(key);
//通过哈希值和当前数据长度,算出当前key值对应在数组中的存放位置
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//如果计算的哈希位置有值(及hash冲突),且key值一样,则覆盖原值value,并返回原值value
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//存放值的具体方法
addEntry(hash, key, value, i);
return null;
}
添加
void addEntry(int hash, K key, V value, int bucketIndex) {
//1、判断当前个数是否大于等于阈值
//2、当前存放是否发生哈希碰撞
//如果上面两个条件否发生,那么就扩容
if ((size >= threshold) && (null != table[bucketIndex])) {
//扩容,并且把原来数组中的元素重新放到新数组中
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
扩容
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//判断是否有超出扩容的最大值,如果达到最大值则不进行扩容操作
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
// transfer()方法把原数组中的值放到新数组中
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//设置hashmap扩容后为新的数组引用
table = newTable;
//设置hashmap扩容新的阈值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//通过key值的hash值和新数组的大小算出在当前数组中的存放位置
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
扩容操作条件
1、 存放新值的时候当前已有元素的个数必须大于等于阈值
2、 存放新值的时候当前存放数据发生hash碰撞(当前key计算的hash值换算出来的数组下标位置已经存在值)
扩容过程
2倍长度
移动数据,重新进行indexFor
1.8知识点
数组 +链表+红黑树,
当链表超过8时,链表会转为红黑树。
计算hash
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
put数据过程
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
// 判断 是否有key
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);
// 判断是否大于等于7时 需要变树
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;
}
扩容
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;
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.7 与1.8的区别
- 插入方式
JDK1.7用的是头插法,而JDK1.8及之后使用的都是尾插法,
那么他们为什么要这样做呢?
因为JDK1.7是用单链表进行的纵向延伸,当采用头插法时会容易出现逆序且环形链表死循环问题。
但是在JDK1.8之后是因为加入了红黑树使用尾插法,能够避免出现逆序且链表死循环的问题。
- 扩容后数据存储位置的计算方式也不一样:
在JDK1.7的时候是直接用hash值和需要扩容的二进制数进行&(这里就是为什么扩容的时候为啥一定必须是2的多少次幂的原因所在,
因为如果只有2的n次幂的情况时最后一位二进制数才一定是1,这样能最大程度减少hash碰撞)(hash值 & length-1)
HashMap 说明
*基于哈希表的<tt>Map</tt>接口的实现。这个
*实现提供所有可选的map操作和许可证
*<tt>null</tt>值和<tt>null</tt>键。(HashMap的<tt>
*类与Hashtable</tt>大致等价,只是
*这个类不保证
*地图的顺序;特别是,它不能保证
*会随着时间的推移保持不变。
*
*<p>此实现为基本
*操作(<tt>get</tt>和<tt>put</tt>),假设哈希函数
*在桶中适当分散元素。重复
*集合视图所需的时间与
*<tt>HashMap</tt>实例(bucket的数量)加上它的大小(数量
*键-值映射)。因此,不要设置初始值是非常重要的
*如果迭代性能为
*很重要。
*
*<p>HashMap的实例有两个影响其
*性能:<i>初始容量</i>和<i>负载系数</i>。这个
*<i>capacity</i>是哈希表中的存储桶数,以及
*容量就是创建哈希表时的容量。这个
*<i>loadfactor</i>是一种度量哈希表的完整程度的度量
*在其容量自动增加之前获取。当
*哈希表中的条目超过了加载因子和
*当前容量,哈希表被重新哈希化(即内部数据)
*结构被重建),因此哈希表的
*铲斗数量。
*
*<p>一般来说,默认负载系数(.75)提供了一个良好的
*在时间和空间成本之间进行权衡。较高的值会降低
*空间开销但是增加了查找成本(反映在
*HashMap</tt>类的操作,包括
*<tt>获取</tt>和<tt>放置</tt>)。中的预期条目数
*当
*设置其初始容量,以便将
*重新洗刷作业。如果初始容量大于
*最大条目数除以负载系数,无需重新计算
*行动永远都会发生。
*
*<p>如果许多映射要存储在一个<tt>HashMap中</tt>
*实例,以足够大的容量创建它将允许
*将映射存储起来比让它执行更有效
*根据需要自动重洗以增加桌子。注意使用
*使用相同的{@code hashCode()}的多个键肯定会减慢速度
*降低任何哈希表的性能。当钥匙
*是{@link Comparable},这个类可以在
*有助于打破联系的钥匙。
*
*<p><strong>请注意,此实现不是同步的。</strong>
*如果多个线程同时访问一个哈希映射,并且至少有一个
*线程在结构上修改映射,它必须
*外部同步。(结构修改是指任何操作
*添加或删除一个或多个映射;仅更改值
*与实例已包含的键关联的不是
*结构修改)这通常是通过
*在一些自然封装地图的对象上同步。
*
*如果不存在这样的对象,则应该使用
*{@link Collections\synchronizedMap集合.synchronizedMap}
*方法。这最好在创作时进行,以防意外
*对地图的非同步访问:<pre>
*地图m=集合.synchronizedMap(新的HashMap(…);</pre>
*
*<p>该类的所有“集合视图方法”返回的迭代器
*是否快速失效:如果在
*迭代器是以任何方式创建的,除了通过迭代器自己的方式
*方法,迭代器将抛出一个
*{@link ConcurrentModificationException}。因此,面对
*修改后,迭代器会迅速而干净地失败,而不是冒着风险
*在
*未来。
*
*<p>请注意,迭代器的快速失效行为无法得到保证
*一般来说,在
*存在未同步的并发修改。失败快速迭代器
*尽最大努力抛出ConcurrentModificationException</tt>。
*因此,编写依赖于此的程序是错误的
*其正确性的例外:<i>迭代器的快速失效行为
*应仅用于检测错误。</i>