导读:因map在java面试中经常用到,因此这里写一下,理解及升入一下
文章目录
先了解一下,数据结构-哈希表-哈希函数
导读:宋会英讲数据结构很棒~是我非常喜欢及敬佩的一位老师
哈希表的优点,是能准确定位到哪个位置,直接拿取值,因此放入到哪个位置要根据哈希函数获取放的位置。(效率非常快的)
哈希表也可以叫做散列,视频中讲解了当因哈希函数获取要插入的位置时,发现此位置有元素存在,因此存在的哈希冲突的解决方法,有线性探查法/二次探查法/链表法,java的HashMap就是采用了数组+链表法的形式
视频教学连接:
散列
这里贴一下宋会英老师讲解的链表法的ppt图
根据哈希函数的除于,16%13=3,74%13=9…以此推
当存放的位置冲突时,则用链表法向右扩展
当找元素时,也是根据哈希函数获取位置去查询,然后判断是否要找的元素,如果不是,则去链表法里面去查找
jdk8源代码部署环境
JDK8.0_65源码阅读环境搭建
根据码云地址里去下载下来,更改对应配置执行
分析HashMap如何put
putVal流程图(从网上的拿的,可看参考资料的连接)
put源代码
/**
* 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);
}
/**
* 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
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;
}
从(n - 1) & hash获取了存放到HashMap数组的位置,如果tab[(n - 1) & hash]已经有值,则进行判断是链表还是树形结构,当链表有8个时候,会变成红黑树,方便查找,如图(此图来自javaGuide):
其中hash(key)的代码如下:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
hash(key)的hashCode()源代码如下,因key不同,hashCode()也会随着不同,这里只复制String的HashMap
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
如何获取放的位置
大致操作如下,贴的源代码中有体现途中的操作,慢慢品尝
解析:
>>>16:无符号整体向右移动16位,前面补0
^: 相同则结果为0,不同则结果为1
&: 两位同时为“1”,结果才为“1”,否则为0
上图中得到的位置是5
分析HashMap如何get
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
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;
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;
}
从源代码可以看出(n - 1) & hash获取HashMap数组中的位置,如果key值相等,则返回对应的找到的数据,如果不是,则进行判断是否树结构还是链表结构
HashMap哈希加载因子的用处
导读:在java8里的HashMap的加载因子为0.75,加载因子与扩容有关,通常HashMap初始化的时候容量是16,阈值是16*0.75约等于12,等数组中的元素超过12位时,则要进行扩容,因为扩容是很影响效率,基本上是增大数组的空间,然后将旧的HashMap重塞进去,因此根据实际的数据量来参考。
阈值
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
当数量超过阈值时扩容
if (++size > threshold)
resize();
HashMap如何扩容
扩容源代码
/**
* Initializes or doubles 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;
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;
}
当数量超过阈值后,则进行扩容,容量以2的倍数增大,成32,然后重新在新的数组上根据e.hash & (newCap - 1)位置塞值,及对应的链表和红黑树
HashMap线程不安全实操
待写
JDK1.8与JDK1.7的性能对比实操
待写
总结
这里只是出入HashMap的基本操作,升入和其他细节还是要继续看和思考的,后续会在此篇章上加内容,jdk8针对jdk1.7是有性能上有很大提升,HashMap上引用红黑树,红黑树将在其他篇章写一下,理解一下。
参考资料
Java 8系列之重新认识HashMap
java中的按位与(&)
Java基础知识梳理&HashMap扩容机制和加载因子
Java>>与>>>的区别