HashMap源码之常用方法--JDK1.8
常用方法
hash(key)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
该方法中返回的值是将得到的hash值(传入的值的hashCode方法)的高16位与低16位进行异或操作。这样做的目的在于减少hash之间的碰撞。具体可看这篇:为什么hash将高16位与低16位进行异或操作
V put(K key, V value)
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;
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;
//hashmap中为空方法,在LinkedHashMap中进行了实现,作用为将传入的节点移动到末尾
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
参数:
- hash:通过对传入的key进行hash得到的值
- onlyIfAbsent:如果该值为true,插入数据时只有当key不存在是才插入,否则不进行插入操作
该方法中首先判断当前map中是否存在key,如果不存在则创建一个节点,如果存在根据onlyIfAbsent参数来决定是否进行更新操作。在hashmap中使用数组+链表的形式来保存数据,在保存数据时,对该数进行hash并(n - 1) & hash确定需要插入的数据在数组中的位置。(n - 1) & hash保证得到的数据是散列的且一定在数组中,两个数进行&操作得到的结果一定是小于等于较小的数。而数组存储的实际是一个链表,当数组位置存储的有数据时而另外一个数据也要插入该位置时则链在当前数据的后面。实际存储的事一个包含下一个节点引用的Node节点。当一条链表上存储的节点超过8个时这条链表将会转化为红黑树,更有利于索引与修改等操作。
当计算得到的数组位置没有数据时,直接插入一个新的节点:
tab[i] = newNode(hash, key, value, null);
当需要插入的key-value在map中已有时,进行覆盖操作:
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);
后面的代码就是将需要插入的值包装为一个节点,然后链接到指定数组位置链表的尾节点:
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//将key-value包装为node放在p的后面
p.next = newNode(hash, key, value, null);
//如果该链表的大小达到链表-->红黑树的阈值则进行转化
//TREEIFY_THRESHOLD默认情况下为8
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;
}
V get(Object key)
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;
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;
}
hashmap中的get方法通过调用内部的getNode方法实现,first = tab[(n - 1) & hash]取出key所对应的值。找到需要的值分为以下几步:
- 首先比较取到的first的key与我们传入的key是否相等,如果相等则直接返回first
- 上一步同如果不等,再判断当前first所处的数组位置上的链表是否已经转变为红黑树,如果已经转换为红黑树,那么则调用红黑树的操作来搜索key对应的值,找到则将对应的value返回,没有则返回null
- 如果该位置仍为链表,则通过遍历该链表查找key,找到则将对应的value返回,没有则返回null
boolean containsXxx(Object obj)
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
//遍历数组
for (int i = 0; i < tab.length; ++i) {
//遍历每个数组中的所有元素,查找value
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
containsKey方法同样是调用上面分析的getNode(key)方法,查找步骤一致,找到返回true,没找到则返回false;
V remove(Object key)
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null?null : e.value;
}
//matchValue:为true的情况下必须key-value完全匹配才能进行删除
//movable:只有当链表转化为红黑树,在对树进行操作是才使用该参数,movable为false时在删除指定节点时不移动其他节点
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//p为计算所得数组位置链表上的第一个元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//判断p是否是需要删除的元素
if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//链表已转化为红黑树,从红黑树中找需要的节点
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//遍历链表查找需要的节点
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))) {
//需要删除的节点找到了,进行删除操作
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
//进行了一次修改操作modCount加1
++modCount;
//元素中的数量减1
--size;
//该方法在HashMap中为空方法
//LinkedHashMap中进行了实现,确保在删除过程中LinkedHashMap中进行了实现的首位节点不会发生指向错误
afterNodeRemoval(node);
return node;
}
}
return null;
}
HashMap源码之常用方法--JDK1.8的更多相关文章
- 【Java】HashMap源码分析——常用方法详解
上一篇介绍了HashMap的基本概念,这一篇着重介绍HasHMap中的一些常用方法:put()get()**resize()** 首先介绍resize()这个方法,在我看来这是HashMap中一个非常 ...
- HashMap 源码分析 基于jdk1.8分析
HashMap 源码分析 基于jdk1.8分析 1:数据结构: transient Node<K,V>[] table; //这里维护了一个 Node的数组结构: 下面看看Node的数 ...
- HashMap 源码详细分析(JDK1.8)
一.概述 本篇文章我们来聊聊大家日常开发中常用的一个集合类 - HashMap.HashMap 最早出现在 JDK 1.2中,底层基于散列算法实现.HashMap 允许 null 键和 null 值, ...
- hashmap源码解析,JDK1.8和1.7的区别
背景:hashmap面试基础必考内容,需要深入了解,并学习其中的相关原理.此处还要明白1.7和1.8不通版本的优化点. Java 8系列之重新认识HashMap Java 8系列之重新认识HashMa ...
- HashMap源码分析-基于JDK1.8
hashMap数据结构 类注释 HashMap的几个重要的字段 hash和tableSizeFor方法 HashMap的数据结构 由上图可知,HashMap的基本数据结构是数组和单向链表或红黑树. 以 ...
- HashMap源码解读(jdk1.8)
1.相关常量 默认初始化容量(大小) static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 最大容量 static final int M ...
- HashMap源码解析(JDK1.8)
package java.util; import sun.misc.SharedSecrets; import java.io.IOException; import java.io.Invalid ...
- HashMap源码之构造函数--JDK1.8
构造函数 变量解释 capacity,表示的是hashmap中桶的数量,初始化容量initCapacity为16,第一次扩容会扩到64,之后每次扩容都是之前容量的2倍,所以容量每次都是2的次幂 loa ...
- JDK1.8 HashMap源码
序言 触摸本质才能永垂不朽 HashMap底层是基于散列算法实现,散列算法分为散列再探测和拉链式.HashMap 则使用了拉链式的散列算法,并在JDK 1.8中引入了红黑树优化过长的链表.数据结构示意 ...
随机推荐
- mysql几种关联的区别
1.平时都是用的逗号的模式:select * from a,b where a.id=b.id,逗号的模式等于inner join和join: 2.left join 和 right join相反,效 ...
- Springboot & Mybatis 构建restful 服务三
Springboot & Mybatis 构建restful 服务三 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务二 2 restful ...
- Lambda根据属性名字选择或筛选
using System; using System.Linq.Expressions; internal class LambdaHelper { /// <summary> /// 指 ...
- 从Excel表中导入数据时日期格式的验证问题解决
#region IsDateTimeType 私有方法判断导入数据是否是日期格式 /// <summary> /// 私有方法判断导入数据是否是日期格式 /// </summary& ...
- 做seo应该如何选择网站程序?
网站程序:(具体网站案例,可在官网看到)绝大多数情况下,我们将做的网站有以下几种1.个人博客,推荐的程序Wordpress(php的程序,比较强大),Zblog(asp的程序,比较简单)2.门户网站( ...
- Spring流行的十大理由
Spring大概是每个JAVA程序员都听过的框架,但是它为什么能这么流行? 听到咕泡学院的Tom老师的公开课,下面是他总结的阿里为什么选择Spring的十大理由,我觉得这也是Spring能流行的原因: ...
- Linux 使用记1 fastx toolkit安装问题
1 安装fastx toolkit的时候,步骤按https://blog.csdn.net/LotusWang0723/article/details/78723409 其中可能会出现如下报错 tex ...
- STM32CubeMX的串口配置,以及驱动代码
1.STM32CubeMX的配置没啥子好说的,使能然后改一下波特率和字长,然后在将中断勾选,把中断等级调到1(一定要比systick的优先级垃圾!!!) 2.驱动代码 在生成的it.c文件中,例如用的 ...
- win32控制台程序 宽字符与短字符转化
由于vs各版本之间存在字符设置不兼容问题,特总结char与tchar的互相转换函数,如下,在之后的工程中可以使用. void TcharToChar(const TCHAR * tchar, char ...
- 恢复oracle数据从delete
今天维护系统的时候没仔细看,误删了50行数据,然后想起来以前学过delete语句删除的数据是可以回复的,但是那个时候比较慌乱,也没有心情仔细看,反而是想到了一个歪招解决了问题,我有个良好的嗜好就是经常 ...