本篇从HashMap的put、get、remove方法入手,分析源码流程
(不涉及红黑树的具体算法)
jkd1.8中HashMap的结构为数组、链表、红黑树的形式
 
 
(未转化红黑树时)
 

(转化为红黑树时的情况)


一、关于HashMap需要了解的静态常量

DEFAULT_INITIAL_CAPACITY 数组默认初始容量 16
DEFAULT_LOAD_FACTOR 默认负载因子 0.75
MIN_TREEIFY_CAPACITY 最小树容量 64
在下面的方法探究中将会提到这些静态常量的用处 
 

二、方法探究

1、put

HashMap中的数组是第一次调用put方法时才创建对象的

下面是从进入put到创建完数组的全过程

 

将key、value作为参数传入后,计算key的hash,再传入putVal方法

/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

putVal()的整个流程如下        
1、先判断table是否为null,如果是,调用resize()
 
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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;
}

resize

resize():
判断当前table为null后,初始化负载因子DEFAULT_LOAD_FACTOR
计算当前数组边界DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY
(第一次数组边界为16*0.75=12,当数组超过数组边界时会扩大为两倍。
也就是说数组中的元素达到或大于12时,将第一次扩大数组,大小变为16*2=32)
创建并返回大小为DEFAULT_INITIAL_CAPACITY的table对象。
(总的来说resize负责扩大数组容量和初始化数组)
以上就是调用put方法时HashMap对象内数组的创建过程

2、如果进入putVal()判断table不为null
利用hash值与(&)计算出数组下标,并判断是否为空
如果是,创建node对象并存入数组
如果不是,从当前下标的链表第一位开始一个个往下对比
①若hash和key值都相同,则break退出循环,之后进行value的替换,并返回oldValue
②若过程中遇到null,则创建node对象
  判断是否达到红黑树转换条件:如果当前链表长度达到8,进入treeifyBin方法
  判断表长度(如果小于64,则调用resize(),判断要不要增大数组
  反之replacementTreeNode,用红黑树代替当前链表

(向下遍历数组当前下标链表的操作)

(key相同时value的替换操作)


3、增加size(map中元素的数量)和modCount(对map的操作次数)

2、get

* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

get

将key和key的hash传入getNode方法,并获取返回的Node对象的value
先判断数组不为null,且长度大于0
利用hash值先找到node可能在的列的第一个元素(当前传入key可能不存在)
再竖向遍历链表对比hash和key值

(上面的first即为node可能存在的链表的第一个元素)

查找时如果第一个即匹配则直接返回

否则往下遍历直到匹配或node为null

3、removeNode

/**
* Implements Map.remove and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
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;
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;
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;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

removeNode

与getNode的逻辑类似,利用hash值查找可能存在的位置

如果链表第一位就匹配:

对链表的遍历:

判断node的类型,如果是链表则用node.nest来代替当前位置

最后操作数+1,size-1,返回被remove的node对象

 
 
 
 
 
 
 

HashMap主要方法源码分析(JDK1.8)的更多相关文章

  1. 并发-HashMap和HashTable源码分析

    HashMap和HashTable源码分析 参考: https://blog.csdn.net/luanlouis/article/details/41576373 http://www.cnblog ...

  2. ArrayList源码分析--jdk1.8

    ArrayList概述   1. ArrayList是可以动态扩容和动态删除冗余容量的索引序列,基于数组实现的集合.  2. ArrayList支持随机访问.克隆.序列化,元素有序且可以重复.  3. ...

  3. ReentrantLock源码分析--jdk1.8

    JDK1.8 ArrayList源码分析--jdk1.8LinkedList源码分析--jdk1.8HashMap源码分析--jdk1.8AQS源码分析--jdk1.8ReentrantLock源码分 ...

  4. HashMap原理及源码分析

    HashMap 原理及源码分析 1. 存储结构 HashMap 内部是由 Node 类型的数组实现的.Node 包含着键值对,内部有四个字段,从 next 字段我们可以看出,Node 是一个链表.即数 ...

  5. Java split方法源码分析

    Java split方法源码分析 public String[] split(CharSequence input [, int limit]) { int index = 0; // 指针 bool ...

  6. invalidate和requestLayout方法源码分析

    invalidate方法源码分析 在之前分析View的绘制流程中,最后都有调用一个叫invalidate的方法,这个方法是啥玩意?我们来看一下View类中invalidate系列方法的源码(ViewG ...

  7. Linq分组操作之GroupBy,GroupJoin扩展方法源码分析

    Linq分组操作之GroupBy,GroupJoin扩展方法源码分析 一. GroupBy 解释: 根据指定的键选择器函数对序列中的元素进行分组,并且从每个组及其键中创建结果值. 查询表达式: var ...

  8. HashMap源码分析 JDK1.8

    本文按以下顺序叙述: HashMap的感性认识. 官方文档中对HashMap介绍的解读. 到源码中看看HashMap这些特性到底是如何实现的. 把源码啃下来有一种很爽的感觉, 相信你读完后也能体会到~ ...

  9. HashMap实现原理及源码分析(jdk1.8)

    HashMap底层由数组+链表+红黑树组成,可接受null值,非线程安全 1.基本属性 transient Node<K,V>[] table; //hashmap数组 static fi ...

随机推荐

  1. 毕业设计——基于ZigBee的智能窗户控制系统的设计与实现

    题目:基于物联网的智能窗户控制系统的设计与实现 应用场景:突降大雨,家里没有关窗而进水:家中燃气泄漏,不能及时通风,威胁人身安全,存在火灾的隐患:家中窗户没关,让坏人有机可乘.长时间呆在人多.封闭的空 ...

  2. dfs 例题皇后问题

    题目描述 一个如下的 6 \times 66×6 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行.每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子. 上面的布局可以用序列  ...

  3. Servlet(一)----快速入门

    ## Servlet:server applet *  概念:运行在服务端的小程序 *  servlet就是一个接口,定义了Java类被浏览器访问到(tomcat识别)的规则. *  将来我们自定义一 ...

  4. 动态规划-TSP问题-最短超级串

    2020-03-03 22:55:08 问题描述: 给定一个字符串数组 A,找到以 A 中每个字符串作为子字符串的最短字符串. 我们可以假设 A 中没有字符串是 A 中另一个字符串的子字符串. 示例 ...

  5. MFC之创建多级动态菜单

    一开始以我是这样做的,结果是错误的: 这段代码第一次点击时,会在第6个位置创建MFC菜单,我本以为再次点击,menu->GetSubMenu(5)返回的值就不会为空了,但事实是它返回了NULL, ...

  6. JavaScript超越了Java,c,python等等成为Stack Overflow上最热门的

    JavaScript超越了Java,c,python等等成为Stack Overflow上最热门的标签 在2015年6月至今,JavaScript超越了Java,c,python等等成为Stack O ...

  7. UTF-8 AND UTF-8 without BOM(遇到了这个问题 郁闷了会儿)

    两者的区别: Unicode规范中有一个BOM的概念.BOM——Byte Order Mark,就是字节序标记.在这里找到一段关于BOM的说明: 在UCS 编码中有一个叫做"ZERO WID ...

  8. vim-1-window,buffer and tab

    Summary:A buffer is the in-memory text of a file. A window is a viewport on a buffer. A tab page is ...

  9. NOI ONLINE 提高组 序列 根据性质建图

    题目链接 https://www.luogu.com.cn/problem/P6185 题意 应该不难懂,跳过 分析 说实话第一眼看到这题的时候我有点懵,真不知道怎么做,不过一看数据,还好还好,暴力能 ...

  10. 服务器上安装.NET Framework 3.5 sp1

    操作系统是Windows Server 2008 R2 或 Windows Server 2012 或 Windows Server 2012 R2,可以直接进入“服务器管理器”添加“功能”.