HashMap探究
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回顾
HashMap的原理,内部结构?
底层使用哈希表(数组+链表),当链表过长时会将链表转换为红黑树以实现O(logn)时间复杂度内的查找。
将一下HashMap中put方法的过程
- 对key求hash值,然后再计算下标
- 如果没有碰撞,直接放入桶中
- 如果碰撞了,以链表的形式链接再后面
- 如果链表长度超过阈值,就会把链表转为红黑树
- 如果节点已经存在就替换旧值
- 如果桶满了(容量*负载因子),就需要resize
HashMap中的hash函数时怎么实现的?还有那些hash的实现方式
- 高16bit不变,低16bit和高16bit做异或
- (n-1)& hash 得到下标
- 有哪些Hash的实现方式
HashMap怎么解决冲突,将一下扩容机制,假如一个值在原数组中,现在移动了新数组,位置肯定改变了,那是什么定位到这个新数组中的位置。
- 将新节点加到链表后
- 容量扩充为原来的两倍,然后对每个节点重新计算哈希值
- 这个值只可能在两个地方,一个时原下标位置,另一种是下标为<原下标+原容量>的位置
抛开HashMap,hash冲突有哪些解决方法
- 开放地址发
- 链地址发
针对HashMap中某个Entry链太长,查找时间复杂度可能达到O(n),怎么优化?
- 将链表转换为红黑树
HashMap探究的更多相关文章
- HashMap遍历方式探究
HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: package com.HashMap.Test; import ...
- 【原创】关于hashcode和equals的不同实现对HashMap和HashSet集合类的影响的探究
这篇文章做了一个很好的测试:http://blog.csdn.net/afgasdg/article/details/6889383,判断往HashSet(不允许元素重复)里塞对象时,是如何判定set ...
- HashMap 死循环的探究
大家都知道,HashMap采用链表解决Hash冲突,具体的HashMap的分析可以参考一下http://zhangshixi.iteye.com/blog/672697 的分析.因为是链表结构,那么就 ...
- HashMap原理探究
一.写随笔的原因:HashMap我们在平时都会用,一般面试题也都会问,借此篇文章分析下HashMap(基于JDK1.8)的源码. 二.具体的内容: 1.简介: HashMap在基于数组+链表来实现的, ...
- Java集合系列[3]----HashMap源码分析
前面我们已经分析了ArrayList和LinkedList这两个集合,我们知道ArrayList是基于数组实现的,LinkedList是基于链表实现的.它们各自有自己的优劣势,例如ArrayList在 ...
- java finally深入探究
When---什么时候需要finally: 在jdk1.7之前,所有涉及到I/O的相关操作,我们都会用到finally,以保证流在最后的正常关闭.jdk1.7之后,虽然所有实现Closable接口的流 ...
- SpringCloud学习之DiscoveryClient探究
当我们使用@DiscoveryClient注解的时候,会不会有如下疑问:它为什么会进行注册服务的操作,它不是应该用作服务发现的吗?下面我们就来深入的来探究一下其源码. 一.Springframewor ...
- 细说java系列之HashMap原理
目录 类图 源码解读 总结 类图 在正式分析HashMap实现原理之前,先来看看其类图. 源码解读 下面集合HashMap的put(K key, V value)方法探究其实现原理. // 在Hash ...
- 探究ElasticSearch中的线程池实现
探究ElasticSearch中的线程池实现 ElasticSearch里面各种操作都是基于线程池+回调实现的,所以这篇文章记录一下java.util.concurrent涉及线程池实现和Elasti ...
随机推荐
- 200. Orchard学习 目录
201. Orchard学习 一.基础 210. Orchard学习 二.启动 211. Orchard学习 二 1.Application_Start 212. Orchard学习 二 2.Manu ...
- 解决Android Studio 3.x版本的安装时没有SDK,运行时出现SDK tools错误
好久没更新了,最近手机上的闹钟APP没一个好用的,所以想自己写个. 那Android开发环境搭起来,注意先装好jdk. 1.安装Android Studio google的Android开发网站已经有 ...
- 网络IP地址
IP地址分类 A类网络的IP地址范围为1.0.0.1-127.255.255.254: B类网络的IP地址范围为:128.1.0.1-191.255.255.254: C类网络的IP地址范围为:192 ...
- 嵌套函数变量修改nonlocal & 全局变量修改global
前几天在做一个简单的界面,单击Radiobutton保存字符串,在一个嵌套函数里面修改外部函数.一直不知道怎么修改,上网查了一下,搜关键字“嵌套函数修改变量”,找了好久,才得以解决. 对于python ...
- Find the Top 10 commands in your linux box!
history | awk '{print $2;}' | grep -v '^./' | sort -d | uniq -c | sort -nr | head -n 10 grep, '-v' ...
- Oracle添加定时任务
1.创建存储过程 注:执行语句后,如果需要请添加commit 2.添加定时job,执行存储过程 declare job_delete number; begin dbms_job.submit( jo ...
- server下apache2.4.*虚拟主机配置Forbidden You don't have permission to access / on this server.
前言: 继前面两节笔记之后,在配置一个虚拟主机时,这中间却遇见了一个问题,这里需要描述做一下笔记,刚刚安装的是Ubuntu server,apt-get下来的apache的版本是2.4.7,之前一直用 ...
- [SCOI2015] 情报传递
题目描述 奈特公司是一个巨大的情报公司,它有着庞大的情报网络.情报网络中共有 n 名情报员.每名情报员可能有若干名 (可能没有) 下线,除 1 名大头目外其余 n−1 名情报员有且仅有 1 名上线.奈 ...
- MVC分部视图@Html.Partial
加载分布视图的方式: //1.以视图名使用当前文件夹下的视图(如果没有找到,则搜索 Shared 文件夹) @Html.Partial("_test") //加载对应文件 /Vie ...
- fast-spring-boot快速开发项目
Introduction fast-spring-boot 集成Spring Boot 2.1,Mybatis,Mybatis Plus,Druid,FastJson,Redis,Rabbit MQ, ...