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. C#单元测试分享ppt

    单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证.对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,Java里单元指一个类, ...

  2. Docker国内仓库和镜像

    由于网络原因,我们在pull Image 的时候,从Docker Hub上下载会很慢...所以,国内的Docker爱好者们就添加了一些国内的镜像(mirror),方便大家使用. 一.国内Docker仓 ...

  3. Java使用foreach语句对数组成员遍历输出

    /** * 本程序使用foreach语句对数组成员进行遍历输出 * @author Lei * @version 2018-7-23 */ public class ForeachDemo { pub ...

  4. 漫画 | Servlet属于线程安全的吗?

    Servlet属于线程安全的吗? Servlet不是线程安全的 在JSP中,只有一行代码:<%=A+B %>,运行结果如何? jsp和servlet有什么关系? jsp一般被用在view层 ...

  5. 使用git连接本地和远程github

    使用git连接本地和远程github 网上很多github的流程比较乱,自己尝试整理了一下,主要是步骤较为清晰,如果有不清楚的可详细进行搜索对比 1. 申请和设置github https://gith ...

  6. Docker 启动遇到 Error starting daemon: Error initializing network controller 错误

    docker 版本 1.10.3 一台装有 docker 的机器重启后,没法启动,/var/log/messages 展示如下错误信息: May 17 11:11:14 gziba-hc03 syst ...

  7. Python 操作文件

    open() 函数 模式 说明 r 只读模式 w 只写模式,文件不存在自动创建:存在则清空再写 a 只追加写,在文件最后追加写 r+ 打开一个文件用于读写.文件指针将会放在文件的开头. w+ 打开一个 ...

  8. 进程&线程&协程

    进程  一.基本概念 进程是系统资源分配的最小单位, 程序隔离的边界系统由一个个进程(程序)组成.一般情况下,包括文本区域(text region).数据区域(data region)和堆栈(stac ...

  9. BUGList

    Django : a. MySQL数据表还未创建时,不可在视图内直接使用模型类对象,产生报错 django.db.utils.ProgrammingError: (1146, "Table ...

  10. 10个最佳 Javascript+HTML5 演示文稿框架

    JavaScript 与 HTML5 框架在创建基于现代浏览器的演示文稿时发挥了重要作用.他们把展示插入网页,为演示信息提供了一个有效方式.一般来说,手工插入花费大量事件和精力,它很复杂,以至于新手们 ...