讲讲hashMap?
回答:
作为集合的一种,主要是看它对数据的增删改查操作
- 存
- 取
- 删除
1、是什么?
HashMap
HashMap分为hash(哈希),map(map接口)。简单来说就是实现了map接口,同时利用hash(哈希)实现。
map
map存储结构(key,value),一个key映射一个value。key不可以重复,key,value可以为空,但是key只能允许一次,value为空可以允许多次。
数组,arrayList,linkedList可以视为一种特殊的map,键为索引,值为对象。
查找元素:分为
- 按下标索引查找
- 按内容查找
list的查找效率较低,map的查找效率较高。
map接口:
列举一些方法
public interface Map<K,V> {
V get(Object key);
V put(K key, V value);
boolean containsKey(Object key);
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
//还有很多方法
}
HashMap
hashMap的构造方法有4个
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);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
前三个构造方法主要依赖两个参数:loadFactor(加载因子:默认是0.75)
,initialCapacity(初始容量:默认是16
;最后一个构造方法是接受一个已有额map构造。
为什么(hashMap实现原理)
hashMap内部重要实例变量
transient Node<K,V>[] table;//hashMap的链表数组,(哈希表,哈希桶)
transient int size;//hashMap的大小
int threshold;//hashMap的扩容阈值
final float loadFactor;//hashMap的负载因子
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
table是一个Entry
类型的数组,称为哈希表或者哈希桶,其中的每个元素指向一个单向链表,链表中的每个节点表示一个键值对。Entry是一个内部类。
table的初始值是EMPTY_TABLE,是一个空表,当添加第一个元素时,默认分配的大小是16。扩容时机与threshold
有关,threshold=loadFactor*size。
loadFactor
:负载因子,表示整体上table的占用程度。
默认构造方法
/**
* 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
。
保存键值对
public V put(K key, V value) {
//hash(key):计算key的hash值
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;
//如果table(哈希表)为空
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//resize():扩容方法 默认扩容是2倍
if ((p = tab[i = (n - 1) & hash]) == null)
//如果计算出来的插入下标没有元素,创建一个node插入当前位置
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//数组
//如果插入的位置已经有值,先比较hash值是否一致,再判断key值是否一致
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//红黑树
//判断节点p类型是否是红黑树类型
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//关于红黑树节点的插入后续会讲,现在先讲hashMap相关的
else {
//链表:多个键值对的key的hash值一样,key不一样的就会使用链表进行存储
//如果数组和红黑树都不是,那只能插入到链表中了
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//尾插法,每插入一个节点,bincount自增1
p.next = newNode(hash, key, value, null);
//如果binCout大于链表转换为红黑树的阈值8的时候
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//treeifyBin()方法我们在下面讲
//当链表长度大于8的时候,先去判断数组长度是否大于64,小于的时候去执行`resize()`方法,大于的时候,转化为红黑树。
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//onlyIfAbsent:false,如果为true表示当前节点的value不能被替换
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//afterNodeAccess:hashMap只是提供一个方法,给子类:LinkedHashMap实现,自己什么也不做
afterNodeAccess(e);
return oldValue;
}
}
//更新操作次数,方便遍历的时候检测结构性变化
++modCount;
//插入完成后,size自增+1,并与扩容阈值比较,如果是true,触发resize()进行扩容
if (++size > threshold)
resize();
//afterNodeInsertion: hashMap只是提供一个方法,给子类:LinkedHashMap实现,自己什么也不做
afterNodeInsertion(evict);
return null;
}
如果是第一次保存,首先会调用resize()
方法给table分配实际的空间。
默认的情况下,capatity的值为16,threshold会变成12,table会分配一个长度为16的Entry数组。
接下来,检查key是否为null,如果是,调用putForNullKey单独处理;否则调用hash方法计算key的hash值。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
基于自身的hashCode方法的返回值又进行一些位运算,目的是为了随机性和均匀性。
有了hash值之后,计算应该将这个简直对放到table的哪个位置:
n = (tab = resize()).length;
table[i = (n - 1) & hash]
hashMap中,length为2的幂次方,h&(leng-1) == h%length。
treeifyBin方法
当node,也就是一个单向链表的长度大于8的时候会触发
hashMap的存储结构从链表变成红黑树
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//先判断tab的大小是否大于64,如果是,转成红黑树,否则调用`resize()`方法进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//存储结构转成红黑树,后面讲红黑树的时候再讲
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
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);
}
}
** resize()扩容方法**
对hashMap的大小进行扩容
默认是对size和threshold扩容两倍
扩容时机:
1、size == threshold = size * loadFactor(默认0.75)
2、treeifyBin方法触发的时候,会判断size是否大于64,如果小于,则调用resize()
方法。
//扩容方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//获取当前数组大小oldCap
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//获取当前扩容阈值 oldThr
int oldThr = threshold;
//新的数组大小和新的扩容阈值大小
int newCap, newThr = 0;
if (oldCap > 0) {
//如果当前数组大小超过允许最大范围
if (oldCap >= MAXIMUM_CAPACITY) {
//扩容阈值=Integer的最大值
threshold = Integer.MAX_VALUE;
return oldTab;
}
//新的数组大小=旧的数组大小的2倍 同时 旧的数组大小大于最小数组容量
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//新的扩容阈值 = 旧的扩容阈值 * 2
newThr = oldThr << 1; // double threshold
}
//说明调用了hashmap的有参构造函数,因为无参构造函数并没有对threshold进行初始化
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//16 * 0.75 = 12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
/*以上代码总结:
1.如果已经对底层数组初始化就进行扩容
2.如果数组长度已经是最大整数值了,最大值赋给threshold,不会在进行扩容
3.如果没有达到,数组长度扩展两倍,threshold扩招为原来的两倍
*/
threshold = newThr;
//SuppressWarnings:压制异常
@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)
//e.next == null 的时候表明数组只有一个元素,最简单
//计算在新数组的下标,插入
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//作为红黑树的节点,调用split方法进行处理
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//说明是链表,对链表进行操作
Node<K,V> loHead = null, loTail = null;//loHead:低位链表头,loTail:低位链表尾。低位用于保存在旧数组往新数组移动时下边不变的链表
Node<K,V> hiHead = null, hiTail = null;//hiHead:高位链表头,hiTail:低位链表头。用户保存在移动的过程中,下标更新的链表
Node<K,V> next;
do {
next = e.next;
//节点的key的hash值与原数组的大小 & (与运算),得到的结果为 0 表示在新的数组中下标不变。组成新的链表
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//结果非0的时候,存储在新数组中一个新的位置,形成一个链表
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;
}
到此map.put()
方法执行完毕
map.get()
方法
public V get(Object key) {
Node<K,V> e;
//调用 getNode()方法
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//当前数组不为空,数组长度 > 0,同时根据key.hash值计算得得下标在数组中存在
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;
//如果first.next!=null 表明是链表
if ((e = first.next) != null) {
//是否是红黑树的节点
if (first instanceof TreeNode)
//调用红黑树的getTreeNode方法处理
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;
}
map.remove()删除方法
public V remove(Object key) {
Node<K,V> e;
//调用removeNode方法
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
removeNode方法
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//检查数组是否存在以及是否刚初始化,同时检查要删除的key对应的节点是否存在
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果链表头存的节点是我们要删除的key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//链表头不是我们要删除的key,遍历链表
else if ((e = p.next) != null) {
//链表是单向链表还是红黑树
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
//单向链表
else {
//遍历链表,找到我们要删除的key
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//node:表示要删除的节点
//p: 表示tab[key.hash & size - 1] 的得到的值,不一定是要删除的值,hash冲突问题
//matchValue:默认为false,if true only remove if value is equal
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//如果node是红黑树
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//如果node为数组
else if (node == p)
tab[index] = node.next;
else
//如果node为链表
p.next = node.next;
//操作次数自增1,便于在遍历的时候,检查结构性变化
++modCount;
//数组大小自减1
--size;
//afterNodeRemoval:留给LinkedHashNode实现的方法
afterNodeRemoval(node);
return node;
}
}
return null;
}