1.HashMap 的原理,内部数据结构?
底层使用哈希表(数组加链表),当链表过长会将链表转成 红黑树 以实现0(logn)时间复杂度内查找
2.将下HashMap中put方法过程?
i.对key求hash值,然后再计算 下标
ii:如果没有碰撞,直接放入桶中
iii:如果碰撞了,以链表的方式连接到后面
iv:如果链表的长度超过阀值(TREEIFY_THRESHOLD==8),就把链表转成红黑树。
v:如果节点已经存在就替换旧值
vi:如果桶满了(容量*加载引子),就需要resize。
3.HashMap中hash函数怎么是实现?还有那些hash的实现方式?
i:高16bit不变,低16bit与高16bit做一个与或
ii: (n-1)&hash-->得到下标
iii:还有那些hash的实现方式:可以参考之前的博客 Effective java 学习笔记--hashcode()
4.hashmap如何解决冲突,讲一下扩容过程,加入一个值在原数组中,现在移动之后变为新数组,位置肯定改变了,那是什么定位到这个值新数组中的位置
- 将新节点加到数组后面后
- 容量扩充为原来的两倍,然后对每个节点重新计算hash值
这个值只可能在两个地方,一个是原下标的地方,另一个是在下标为<原下标+原容量>的位置
5 抛开hashMap, hash冲突有哪些解决办法?
开放地址,链地址法
6.针对hashmap中的某个entry链太长,查找的时间复杂度可能达到O(n),怎么优化?
。 将链表转化为红黑树,JDK1.8 已经实现
7 hashMap链表的插入用的是头插法还是尾插法,为什么?
JDK1.7 头插法--> 因为链表长-》不用遍历链表后面所有的元素-》缺点:头插法 要将链表后面的所有元素后移
JDK1.8 尾插法--》因为链表短-》仅需遍历有限链表结点
数据在计算机中的存储结构(数据结构)
1.数组
2.链表
23树结构
数组(ArrayList)
链表(linklist)
双向链表 :查询效率低 增删效率高
HashMap 数组加链表
数组的表示
数组的初始化容量 最大容量 加载因子
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
数组的大小可能不够用 :扩大
什么时候扩大: 16*0.72=12(原大小*加载因子) 数组扩大的标准 首次用到12的时候扩大
链表的长度可以无限变大吗?不可以 链表的长度超过treeify_threshold=8时 链表转化为红黑树
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
链表和红黑树有各自最优效率的元素数量 当红黑树中的元素小于 untreeify_threshold=6时将转化回链表
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
每次向数组中添加元素 都会记录已经使用的格子数量,当size大于 16*0.72=12(原大小*加载因子 数组扩大的标准)时 resize()
来了一个key,value组成了Node节点之后,这个节点到底该何去何从?
生产出一个算法 hash()算法
1, 返回一个 int类型的值
key,value ------>key(Object) 有个hashcode()方法得到key的hash值 :3254239
2, 0~15之间 数组大小的范围内
hash%16=0~15
3,尽可能利用数组的每一个位置
注意node节点的属性 key的hash, key,value,next下一个节点
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
新来一个节点调用put() 根据hash(key)计算hash值(对hashCode()的值进行高十六位和低十六位运算)
在putval()中新节点的到来分为三种情况
1 table数组原来的位置为空
2 table数组原来的位置不为空,且下面是链表的结构
3 table数组原来的位置不为空,且下面是红黑树的结构
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//取key的hashcode() 与 hashcode()的低十六位运算结果 做异或运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 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)//根据key的hash值计算该note节点在数组中的角标 判断该角标位数元素是否为空
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))//table数组原来的位置不为空,且下面是红黑树的结构
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) //超过12 则去扩容
resize();
afterNodeInsertion(evict);
return null;
}
/**
* Initializes or doubles table size. 初始化或扩容table数组的size If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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;//默认大小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);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//初始化一个默认大小16的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;
}
分析
(n - 1) & hash
hash为 根据hash(key)计算hash的值(对hashCode()的值与hashCode()的低16位进行异或运算) 例 :3254239
n为数组初始化的长度16
即为 15&3254239 转化为 2进制 &运算 结果在0000到1111(0~15)之间
所以数组的大小永远是2的n次幂 以保证得到的结果在0到15之间
如何保证尽可能利用数组的每一个位置?
需保证hash的值足够分散 对对hashCode()的值与hashCode()的低16位进行异或运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}