HashMap

前置
//初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//容器最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子,在0.75的时候扩大。比如16的时候,12扩大 12/16=0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//Node超过8时,转换为红黑树。
//查找由链表的O(n)转换为O(log(n)) 对数级
static final int TREEIFY_THRESHOLD = 8;

Node

  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;
}

数组:

 transient Node<K,V>[] table;
put操作
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//为空则初始化Node[]数组
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//判读数组位置是否有Node占据,如果没有,直接复制
if ((p = tab[i = (n - 1) & hash]) == null)
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;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//p相当于数组坐标的位置
//把数据插入链表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果大于TREEIFY_THRESHOLD即是大于等于7,说明链表长度为8了,做转换操作
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//判断hash和key是否相等,如果相等,则进行更新操作
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;
//数组到底用了多少个格子
//threshold记录的是当前数组格子用了多少,超出大小*负载因子则需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
get操作
    public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

hash操作

    static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
resize
 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;
}

问题要点

数据结构:链表+数组

// 链表
node{
object key
object value
Node next
}
//数组
elemDate[]

hash函数实现

    static final int hash(Object key) {
int h;
//低16位和高16位异或,右移后异或,保证hash分散,降低重复率。防止数组后面的链表过长,尽可能用齐数组
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
} public native int hashCode();

检查是否hash碰撞

  if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);

成员变量:threshold 记录数组用了多少。易混static final int TREEIFY_THRESHOLD = 8; 为链表转红黑树的大小。

        //数组到底用了多少个格子
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
        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;

resize()方法:Initializes or doubles table size 初始化或者双倍扩容 以双倍扩容 (n-1)&hash与也可以体现出来

////雨露均沾,链表上的值,分配到新的数组上
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
                           if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}

HashMap回顾

  1. HashMap的原理,内部结构?

    底层使用哈希表(数组+链表),当链表过长时会将链表转换为红黑树以实现O(logn)时间复杂度内的查找。

  2. 将一下HashMap中put方法的过程

    1. 对key求hash值,然后再计算下标
    2. 如果没有碰撞,直接放入桶中
    3. 如果碰撞了,以链表的形式链接再后面
    4. 如果链表长度超过阈值,就会把链表转为红黑树
    5. 如果节点已经存在就替换旧值
    6. 如果桶满了(容量*负载因子),就需要resize
  3. HashMap中的hash函数时怎么实现的?还有那些hash的实现方式

    1. 高16bit不变,低16bit和高16bit做异或
    2. (n-1)& hash 得到下标
    3. 有哪些Hash的实现方式
  4. HashMap怎么解决冲突,将一下扩容机制,假如一个值在原数组中,现在移动了新数组,位置肯定改变了,那是什么定位到这个新数组中的位置。

    1. 将新节点加到链表后
    2. 容量扩充为原来的两倍,然后对每个节点重新计算哈希值
    3. 这个值只可能在两个地方,一个时原下标位置,另一种是下标为<原下标+原容量>的位置
  5. 抛开HashMap,hash冲突有哪些解决方法

    1. 开放地址发
    2. 链地址发
  6. 针对HashMap中某个Entry链太长,查找时间复杂度可能达到O(n),怎么优化?

    1. 将链表转换为红黑树

HashMap探究的更多相关文章

  1. HashMap遍历方式探究

    HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: package com.HashMap.Test; import ...

  2. 【原创】关于hashcode和equals的不同实现对HashMap和HashSet集合类的影响的探究

    这篇文章做了一个很好的测试:http://blog.csdn.net/afgasdg/article/details/6889383,判断往HashSet(不允许元素重复)里塞对象时,是如何判定set ...

  3. HashMap 死循环的探究

    大家都知道,HashMap采用链表解决Hash冲突,具体的HashMap的分析可以参考一下http://zhangshixi.iteye.com/blog/672697 的分析.因为是链表结构,那么就 ...

  4. HashMap原理探究

    一.写随笔的原因:HashMap我们在平时都会用,一般面试题也都会问,借此篇文章分析下HashMap(基于JDK1.8)的源码. 二.具体的内容: 1.简介: HashMap在基于数组+链表来实现的, ...

  5. Java集合系列[3]----HashMap源码分析

    前面我们已经分析了ArrayList和LinkedList这两个集合,我们知道ArrayList是基于数组实现的,LinkedList是基于链表实现的.它们各自有自己的优劣势,例如ArrayList在 ...

  6. java finally深入探究

    When---什么时候需要finally: 在jdk1.7之前,所有涉及到I/O的相关操作,我们都会用到finally,以保证流在最后的正常关闭.jdk1.7之后,虽然所有实现Closable接口的流 ...

  7. SpringCloud学习之DiscoveryClient探究

    当我们使用@DiscoveryClient注解的时候,会不会有如下疑问:它为什么会进行注册服务的操作,它不是应该用作服务发现的吗?下面我们就来深入的来探究一下其源码. 一.Springframewor ...

  8. 细说java系列之HashMap原理

    目录 类图 源码解读 总结 类图 在正式分析HashMap实现原理之前,先来看看其类图. 源码解读 下面集合HashMap的put(K key, V value)方法探究其实现原理. // 在Hash ...

  9. 探究ElasticSearch中的线程池实现

    探究ElasticSearch中的线程池实现 ElasticSearch里面各种操作都是基于线程池+回调实现的,所以这篇文章记录一下java.util.concurrent涉及线程池实现和Elasti ...

随机推荐

  1. (转)你真的会写单例模式吗——Java实现

    http://www.runoob.com/design-pattern/singleton-pattern.html 单例模式可能是代码最少的模式了,但是少不一定意味着简单,想要用好.用对单例模式, ...

  2. 信号为E时,如何让语音识别脱“网”而出?

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由腾讯教育云发表于云+社区专栏 一般没有网络时,语音识别是这样的 ▽ 而同等环境下,嵌入式语音识别,是这样的 ▽ 不仅可以帮您边说边识. ...

  3. rtf格式 C#设置字间距 CharacterSpacing

    richtextbox空间中操作行间距段间距都可以用发送消息解决,但是字间距却鲜有人关注,无法通过PARAFORMAT2消息解决,只能直接操作rtf格式 字间距主要就是要控制 expand expan ...

  4. 单例模式写MySQL model类,简单的增、删、改、查

    单例模式的用途,可用于数据库操作 <?php Class Db { static private $whe;//条件 static private $tab;//表名 static privat ...

  5. python中逻辑运算符“+”的特殊之处

    num = num + num 与 num += num 的区别(其他语言中这两种方式可以划等号,但是python中不可以): num = num + num: num = [100] def tes ...

  6. C#常用单元测试框架比较:XUnit、NUnit和Visual Studio(MSTest)

    做过单元测试的同学大概都知道以上几种测试框架,但我一直很好奇它们到底有什么不同,然后搜到了一篇不错的文章清楚地解释了这几种框架的最大不同之处. 地址在这里:http://www.tuicool.com ...

  7. Hive案例05-学生成绩表综合案例

    1. 数据说明 (1) student表 hive> select * from student; # 学生ID 学生姓名 性别 年龄 所在系 # sid sname sex age dept ...

  8. [PHP] 算法-把数组排成最小的数的PHP实现

    输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 解法1 1.数组排序, ...

  9. Intellij Idea乱码解决方案

    使用Intellij Idea经常遇到的三种乱码问题: 1.工程代码乱码 2.main方法运行,控制台乱码 3.tomcat运行,控制台乱码 解决方案: 1.工程代码乱码 Settings > ...

  10. 【常用配置】Hadoop-2.6.5在Ubuntu14.04下的伪分布式配置

    core-site.xml <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet t ...