一Hashmap
Hashmap底层数据结构
jdk1.7:hashmap是由数据+链表,jdk1.8:为解决hash冲突,当链表长度大于阈值(默认为8)同时数组长度达到64,将链表转化为红黑树,以减少搜索时间。白话:当数据量太大时将数据结构从链表转换为红黑树,提高检索时间,提高查询效率。官方描述:
*This map usually acts as a binned (bucketed) hash table, but
* when bins get too large, they are transformed into bins of
* TreeNodes, each structured similarly to those in
* java.util.TreeMap
hashmap数据存储
数组存储
查询速度快,插入和删除相对链表来说比较慢,需要将将数组整体移动
链表存储
链表查询较慢,插入和删除先对较快,查询时需要遍历所有链表节点,单链表插入及删除只需要将前一个数的指针,双向俩表需要修改前一个数以及后一个数的指针
Hashmap中put与get
- hash中put时,通过key的hash算法值存储当前对象,源码:
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
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时,如果发现key相同,则将value覆盖,若key不同,则将当前的key-value对象存储到链表中
-
get时,通过hash值遍历hash表,若寻找到,则判断key值是否相等,源码如下:
final Node<K,V> getNode(Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != 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;
}
hashmap与LinkedHashmap区别
- 由于HashMap是以key的hash算法存储对象所以存储时是无序的,LinkedHashMap存储的是有序列表,
- LinkedHashMap有序实现原理:LinkedHashMap根据key的hash值存储的链表。它采用了HashMap和LinkedList的结合,内部使用一个双向链表来维护插入顺序。通过使用双向链表,LinkedHashMap可以记录元素的插入顺序,并且可以实现快速的访问和遍历操作。
- 总结:若对存取顺序保持一致性,则使用LinkedHashMap结构存储key-value键值对对象