UML类图

java.util.Map<K, V>接口,有4个实现类:HashMapHashtableLinkedHashMapTreeMap

1、说明

(1)HashMap除允许键值为null、非线程安全。
使用散列存储方式存储键值,数据存储无序。如果想要使用有序存储可以使用LinkedHashMap。
性能上当HashMap中保存的key的哈希算法能够均匀的分布在每个bucket(位桶)中的时候,HashMap在基本的get和set操作的的时间复杂度都是O(n)。
遍历HashMap的时候,其遍历节点的个数为bucket(位桶)个数+HashMap中保存的节点个数。因此当遍历操作频繁时需要注意HashMap的初始化容量不应该设置太大。 这一点比较好理解:当保存的节点个数一致的时候,bucket越少,遍历次数越少。
另外HashMap在resize时会有很大的性能消耗,所以在HashMap中存储大量数据时,传入适当默认容量值以避免resize可以有效提高性能。 具体的resize操作请参考下面对此方法的分析。

HashMap采用桶+链表+红黑树(自平衡二叉查找树)数据结构,当链表长度超过阈值(8)且长度大于64时,将链表转换为红黑树以减少查找时间。

(2)Hashtable与HashMap相似,不同的之处:继承Dictionary类、线程安全(并发效率不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁)。Hashtable不建议在代码中使用,不需要线程安全的场合用HashMap替换,需要线程安全的场合用ConcurrentHashMap替换。

(3)LinkedHashMap是HashMap的一个子类,数据存储有序。

(4)TreeMap实现SortedMap接口,数据存储有序根据键排序(默认按键值升序排序,也可以指定排序比较器)。

对于上述四种类型Map,要求映射中的key是不可变对象。不可变对象,对象在创建后哈希值不会被改变。如果对象哈希值发生变化,Map对象很可能就定位不到映射位置。

2、成员属性

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始化容量16
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认加载因子
static final int TREEIFY_THRESHOLD = 8; //当put一个元素到某个位桶,如果其链表长度达到8时将链表转换为红黑树
static final int UNTREEIFY_THRESHOLD = 6; //
static final int MIN_TREEIFY_CAPACITY = 64; // transient Node<K,V>[] table; //哈希桶数组
transient Set<Map.Entry<K,V>> entrySet; //
transient int size; //元素个数
transient int modCount; //结构变更次数
int threshold; //扩容阈值
final float loadFactor; //加载因子 

3、构造方法

    public HashMap() { //无参数构造方法;默认初始容量16;加载因子0.75f;
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted//loadFactor = 0.75f:加载因子。其他成员默认。
}
    public HashMap(int initialCapacity) { //初始容量initialCapacity;默认加载因子0.75f
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
       public HashMap(int initialCapacity, float loadFactor) { //初始容量initialCapacity;初始加载因子: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);
}
    /**
* Returns a power of two size for the given target capacity.
   * 计算初始化容量,
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1; //n右移1;按位或赋值给n
n |= n >>> 2; //n右移2;按位或赋值给n
n |= n >>> 4; //n右移4;按位或赋值给n
n |= n >>> 8; //n右移8;按位或赋值给n
n |= n >>> 16; //n右移16;按位或赋值给n
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

4、成员方法

//确定Hash桶的位置
//第一步:h = key.hashCode(),计算hashCode
//第二步:h = h ^ (h >>> 16),异或运算
//第三步:(n - 1) & h,与运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

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;
if ((tab = table) == null || (n = tab.length) == 0)
//①判断添加第一个元素
n = (tab = resize()).length; //添加一地个元素
if ((p = tab[i = (n - 1) & hash]) == null)
//②判断table的在(n-1) & hash索引值是否空,如果空创建一个节点插入次位置
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))))
//③判断第一个Node是否是要找的值
e = p;
else if (p instanceof TreeNode)
//④红黑树处理
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //
else {
//⑤遍历插入键值对
          for (int binCount = 0; ; ++binCount) { //累积hash冲突数量
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null); //
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); //判断Hash桶长度是否小于64,是resize扩容,否存储结构转换为红黑树
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) //如果key已经存在,停止遍历
break;
p = e;
}
}
if (e != null) { // existing mapping for key //查到key已存在,更新对应value值
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value; //节点赋值新值
afterNodeAccess(e);
return oldValue; //返回旧值
}
}
++modCount;
if (++size > threshold) //⑥判断键值对数量是否大于阈值,是进行扩容
resize(); //扩容
afterNodeInsertion(evict);
return null;
}  
//扩容机制
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;//hash桶数组
int oldCap = (oldTab == null) ? 0 : oldTab.length;//老的hash桶数组长度
int oldThr = threshold;//老的阈值
int newCap, newThr = 0;
if (oldCap > 0) {//①如果大于0
if (oldCap >= MAXIMUM_CAPACITY) { //容量大于等于最大容量
threshold = Integer.MAX_VALUE; //阈值等于int最大值
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold //容量*2
}
else if (oldThr > 0) //②使用阈值初始化容量
newCap = oldThr;
else {//③使用默认值初始化容量
newCap = DEFAULT_INITIAL_CAPACITY; //初始化默认容量:16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //初始化默认阈值:加载因子(0.75f) * 初始化容量(16)
}
if (newThr == 0) { //④如果新阈值=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) { //遍历旧hash桶数组
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 { //遍历hash桶数组j元素链表或红黑树
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;

 //链表数据结构

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;
}

public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }

public final int hashCode() {
  return Objects.hashCode(key) ^ Objects.hashCode(value);
}

public final V setValue(V newValue) {
  V oldValue = value;
  value = newValue;
  return oldValue;
}

//判断两个Node节点是否相同

public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}

//红黑树数据结构    
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; //父节点
TreeNode<K,V> left; //左子树
TreeNode<K,V> right; //右子树
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red; //颜色属性
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
} /**
* Returns root of tree containing this node.
      * 返回根节点
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
。。。其他省略。。。

get方法源码分析:

    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) {//①查找hash桶
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))//判断查询的key是否链表节点,是直接返回
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;
}

5、demo程序,查看数据结构(散列数组+链表)

package com.javabasic.map;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; /**
* 源码分析
*
*
* 允许使用null键和null值;
* 线程不同步,效率高;
*
*
* @author wangymd
*
*/
public class HashMapTest2 { public static void main(String[] args) {
Stu stu1 = new Stu(1,"xiaojia");
Stu stu2 = new Stu(1,"xiaoyi");
Stu stu3 = new Stu(1,"xiaobing");
Stu stu4 = new Stu(1,"xiaoding"); Map<Stu, String> hm = new HashMap<Stu, String>();
hm.put(stu1, "xiaojia");
hm.put(stu2, "xiaoyi");
hm.put(stu3, "xiaobing");
hm.put(stu4, "xiaoding"); Set<Entry<Stu, String>> entrySet = hm.entrySet(); //断点,查看数据结构;如下图
for (Entry<Stu, String> entry : entrySet) {
Stu key = entry.getKey();
String value = entry.getValue();
System.out.println(key.getName() + "----" + value);
}
} } class Stu{ Integer id;
String name;
public Stu() {} public Stu(Integer id, String name) {
this.id = id;
this.name = name;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

参考:

https://zhuanlan.zhihu.com/p/21673805 (HashMap源码分析)

https://blog.csdn.net/v_july_v/article/details/6105630 (红黑树)


//hash桶数组

最新文章

  1. Python 修改电脑DNS
  2. Photoshop如何实现UI自动切图?
  3. awk 合并文件
  4. 续Gulp使用入门编译Sass
  5. 非在线方式搭建Android开发环境
  6. js 正则表达式 手机号
  7. MyEcpilise引入Maven项目目录不正常,无JRE,无Maven Dependencies
  8. Linux删除以破折号开头的文件Windows在批处理文件来删除隐藏属性
  9. C# 中的常用正则表达式总结
  10. Android进阶(二十)AndroidAPP开发问题汇总(四)
  11. laravel 开启定时任务需要操作
  12. 括号生成(Java实现)
  13. 侧脸生成正脸概论与精析(一)Global and Local Perception GAN
  14. pytbull:入侵检测/预防系统测试框架 (转)
  15. No.1000_第五次团队会议
  16. cocos2d-x3.0 macOS下配置Android开发环境以及使用cocos2d-console来新建执行project
  17. bitbucket SSH 生成
  18. 原生js追加Html 或者text
  19. JavaScript之链式结构序列化1
  20. mysql进阶二

热门文章

  1. Shell脚本定时监控
  2. Codeforces1144A(A题)Diverse Strings
  3. Python的概述
  4. HTML标签和属性三
  5. MySQL的列约束
  6. kudu_单master集群安装
  7. 王艳 201771010127《面向对象程序设计(Java)》第四周学习总结
  8. Hyperledger Fabric Node SDK和应用开发
  9. Unity 游戏框架搭建 2019 (四十八/四十九) MonoBehaviourSimplify 中的消息策略完善&amp;关于发送事件的简单封装
  10. 【LINQ标准查询操作符总结】之聚合操符