源自:jdk1.8.0_121

HashMap继承自AbstractMap,实现了MapCloneableSerializable

HashMap内部是由数组、链表、红黑树实现的

变量

    // 默认大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30; // 默认负载因子,默认0.75,当数组
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 链表长度大于8的时候转红黑树
static final int TREEIFY_THRESHOLD = 8; // 红黑树节点小于6的时候转链表
static final int UNTREEIFY_THRESHOLD = 6; // 转换为红黑树之前还得判断数组的容量是否大于64
static final int MIN_TREEIFY_CAPACITY = 64; // 数组
transient Node<K,V>[] table; transient Set<Map.Entry<K,V>> entrySet; // 数组table的大小
transient int size; // 操作次数
transient int modCount; /**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
// 这个注释很关键,如果table数组还没被分配时,阈值threshold等于数组的数组容量,反之threshold = capacity * load factor
int threshold; // 负载因子
final float loadFactor;

构造方法

    public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
} public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
} public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
} public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

put方法

    public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
} final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果数组为null或者数组的大小为0时,对数组进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 因为n为2的a次,(2^a - 1) & hash < 2^a,所以不会越界,当tab[i]为空时(索引不冲突),直接插入数组中
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;
// 当p为红黑树时
else if (p instanceof TreeNode)
// Node转型TreeNode*
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 当p为链表时
else {
// 一直循环到链表的最后一个结点
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 当结点数大于等于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;
}
}
// hash和key都冲突时,e才会不等于null
if (e != null) { // existing mapping for key
V oldValue = e.value;
// 如果onlyIfAbsent为false就不会替换原有的值
if (!onlyIfAbsent || oldValue == null)
// 替换原有的值
e.value = value;
afterNodeAccess(e);
// 返回被替换的值
return oldValue;
}
}
++modCount;
// 超过最大容量(length * Load factor)时,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

tableSizeFor方法

    // 返回一个最接近cap的2^n幂
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

get方法

    // 通过key的和key的hash获取值
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
} final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 首先获取这个key所在的哪一个链表或者红黑树
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 如果头结点的key和hash都与要查找的相等时,直接返回头结点
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);
// 链表,就一直循环到匹配到的key,否则返回null
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

treeifyBin方法

    // 将Node结点转换成TreeNode结点(其实也就是TreeNode结点的双向链表)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 数组为空或者数组的大小小于64,扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
// 第一个结点不为空时
else if ((e = tab[index = (n - 1) & hash]) != null) {
// hd 头结点,tl 尾结点
TreeNode<K,V> hd = null, tl = null;
do {
// 将Node结点转换成TreeNode结点
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
// 将红黑树结点树形化
hd.treeify(tab);
}
}

内部类

HashMap$TreeNode类(红黑树结点)

红黑树的特性

  1. 每个结点是红色或者黑色。
  2. 根结点是黑色。
  3. 每个叶子节点(NIL)是黑色。
  4. 如果一个节点是红色的,则它的子节点必须是黑色的。
  5. 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。

treeify方法

将红黑树结点树形化,变成红黑树的结构。【暂未深入了解】

        final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
// 确认根结点,黑色
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
// 根结点(p)的hash > 要插入结点(x)的hash时
// 插入到根结点的左边
if ((ph = p.hash) > h)
dir = -1;
// 插入到根结点的右边
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk); TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}

getTreeNode方法

        final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
} final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}

疑问?

hash % 2^n == hash & (2^n-1)

hash % 2^n 余数是0~2^n-1

hash & (2^n-1) ,也就是取hash的后n位,后n位最大值是2^n-1

当hash = n时

hash n hash % 2^n hash & (2^n-1)
0 0 0 0
1 1 1 1
... ... ... ...
n n n n

当hash = n-a时(hash < n)

hash n hash % 2^n hash & (2^n-1)
0 a 0 0
1 a+1 1 1
... ... ... ...
n-a n n-a n-a

当hash = n+a时(hash > n)

hash n hash % 2^n hash & (2^n-1)
0 -a 0 0
1 -a+1 1 1
... ... ... ...
n+a n n+a n+a

综上所述hash % 2^n == hash & (2^n-1)成立。

Node转型TreeNode(向下转型)

NodeTreeNode都是HashMap的内部类,怎么还能转型的呢?

    // 在HashMap里内部类TreeNode继承了LinkedHashMap的内部类Entry
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
    // 在LinkedHashMap里内部类Entry又继承了HashMap的内部类Node
static class Entry<K,V> extends HashMap.Node<K,V>

java集合之HashMap源码解读的更多相关文章

  1. 【转】Java集合:HashMap源码剖析

    Java集合:HashMap源码剖析   一.HashMap概述二.HashMap的数据结构三.HashMap源码分析     1.关键属性     2.构造方法     3.存储数据     4.调 ...

  2. 【JAVA集合】HashMap源码分析(转载)

    原文出处:http://www.cnblogs.com/chenpi/p/5280304.html 以下内容基于jdk1.7.0_79源码: 什么是HashMap 基于哈希表的一个Map接口实现,存储 ...

  3. Java集合:HashMap源码剖析

    一.HashMap概述 HashMap基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了不同步和允许使用 null 之外,HashMap  ...

  4. 【Java集合】ArrayDeque源码解读

    简介 双端队列是一种特殊的队列,它的两端都可以进出元素,故而得名双端队列. ArrayDeque是一种以循环数组方式实现的双端队列,它是非线程安全的. 它既可以作为队列也可以作为栈. 继承体系 Arr ...

  5. Java集合之HashMap源码实现分析

    1.简介 通过上面的一篇随笔我们知道了HashSet的底层是采用Map实现的,那么Map是什么?它的底层又是如何实现的呢?这下我们来分析下源码,看看具体的结构与实现.Map 集合类用于存储元素对(称作 ...

  6. 死磕 java集合之HashMap源码分析

    欢迎关注我的公众号"彤哥读源码",查看更多源码系列文章, 与彤哥一起畅游源码的海洋. 简介 HashMap采用key/value存储结构,每个key对应唯一的value,查询和修改 ...

  7. java集合之HashMap源码解析

    Map是java中的一种数据结构,围绕着Map接口,有一系列的实现类如Hashtable.HashMap.LinkedHashMap和TreeMap.而其中HashMap和Hashtable我们平常使 ...

  8. java集合之ArrayList源码解读

    源自:jdk1.8.0_121 ArrayList继承自AbstractList,实现了List.RandomAccess.Cloneable.Serializable. ArrayList内部是通过 ...

  9. Java集合之HashMap源码分析

    以下源码均为jdk1.7 HashMap概述 HashMap是基于哈希表的Map接口的非同步实现. 提供所有可选的映射操作, 并允许使用null值和null健. 此类不保证映射的顺序. 需要注意的是: ...

随机推荐

  1. sql 几种循环方式

    1:游标方式 ALTER PROCEDURE [dbo].[testpro] as ) --日期拼接 ) --仪表编号 ) --数据采集表 ) --数据采集备份表 ) ) begin set @yea ...

  2. ll的命令后面的字段详解

    linux学习 命令ll后字段的解释 分类:linux | 标签: 命令ll后字段的解释  2010-10-25 15:47阅读(4513)评论(0) ls -l 列表信息详解 我们平时用ls -l ...

  3. c#动态加载卸载DLL

    前段时间工作的时候遇到一个问题.就是需要每次启动程序的时候动态替换掉某个dll,所以就百度了这方面的资料.这次记录下来让自己以后可以看. 根据自己的理解,动态卸载dll需要有以下条件: 1:dll在加 ...

  4. OAuth2.0学习(1-9)新浪开放平台微博认证-web应用授权(授权码方式)

    1. 引导需要授权的用户到如下地址: URL 1 https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&respons ...

  5. 理解Node.js安装及模块化

    1.安装Node Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. Node.j ...

  6. 对scrapy经典框架爬虫原理的理解

    1,spider打开某网页,获取到一个或者多个request,经由scrapy engine传送给调度器schedulerrequest特别多并且速度特别快会在scheduler形成请求队列queue ...

  7. urlopen()&urlretrieve()

    1.urlopen()方法 urllib.request.urlopen(url[,data[,proxies]]) 创建一个表示远程url的类文件对象,然后像本地文件一样的操作这个类文件对象来获取远 ...

  8. Windows使用Gitblit搭建Git服务器

    安装之前需确定安装JAVA运行环境. 下载安装 首先到 Gitblit官网 下载安装包.此处使用的版本是1.8.0. 将解压得到的gitblit-1.8.0文件夹放于C:\gitServer目录下. ...

  9. 单例模式详解及java常用类

    [单例模式]      确保某一个类,只能产生一个实例. 设计思路: ====将构造函数私有化,确保类外部,不能使用new关键字自行创建对象. ====在类内部实例化一个对象,并通过静态方法返回. ( ...

  10. 最新的Windows环境搭建zeroMQ并使用java代码运行zeromq详细教程

    最近项目要用zeromq,linux上很好配置使用,但是windows上配置与使用没有找到合适的解决方案,看的很头疼,这里自己总结下供大家参考 准备工作: 1.libzmq下载地址:https://g ...