HashMap源码解析(初级)
1. 相关问题:为什么用HashMap?
HashMap结合了数组(查找快,插入删除麻烦,扩容麻烦)和链表(插入删除容易,扩容简单,查找慢)的优点,摒弃他们的缺点。
HashMap的特点:快速索引 动态扩容
2.什么是哈希?
核心理论:Hash也称散列、哈希,对应的英文都是Hash,基本原理就是把任意长度的输入,通过Hash算法变成固定长度的输出这个射的规则就是对应的Hash算法,而原始数据映射后的二进制串就是哈希值
Hash特点
- hash值不能反向推导出原始的数据
- 输入数据的微小变化会得到完全不同的hash值,相同的数据会得到相同的值
- 哈希算法的执行效率要高效,长的文本也能快速地计算出哈希值
- hash算法的冲突概率要小
由于hash的原理是将输入空间的值射成hash空间内,而hash值的空间远小于输入的空间根据抽屉原理,一定会存在不同的输入被映射成相同输出的情况。
抽屉原理:桌上有十个苹果,要把这十个苹果放到九个抽屉里,无论怎样放,我们会发现至少会有一个抽屉里面放不少于两个苹果,这一现象就是我们所说的“抽屉原理”
3. 源码解析
首先明确一点 HashMap = 数组+链表+红黑树
目前只分析了最基础的数组+链表的代码实现,没有考虑红黑树
核心方法就那么几个 put resize get remove
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
//一些 静态变量
//缺省(默认)数组table大小 是16 1左移4位
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//table最大长度 2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
//缺省(默认) 负载因子大小 一般不要自己设
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化阈值 参数之一 链表长度超过8 链表变成 红黑树
static final int TREEIFY_THRESHOLD = 8;
//树降级阈值 成为链表
static final int UNTREEIFY_THRESHOLD = 6;
//另一个 树化阈值 整个hash表元素达到64个 才能树化
static final int MIN_TREEIFY_CAPACITY = 64;
//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;
}
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;
}
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;
}
}
//静态公共 方法
/**
* 扰动函数
*
* 让 key的hash值高16位也参与运算(路由寻址)
* 让哈希更加散列 后面寻址 的时候 减少哈希冲突 更加均匀
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//作用 返回一个大于等于当前cap的一个数字 一定是2的次方数
//为什么要-1 因为传入正好是2的次方 计算会变成2的次方*2
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;
}
//成员变量
//哈希表 什么时候初始化 -> 插入元素的时候
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
//当前哈希表中元素个数
transient int size;
//当前哈希表结构修改次数 修改+1
transient int modCount;
//当哈希表中的元素 超过阈值 触发扩容
int threshold;
//负载因子 一般 不要自己设置
final float loadFactor;
/* ---------------- Public operations -------------- */
//构造方法 最重要的
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);
//一般都是默认0.75
this.loadFactor = loadFactor;
//必须是2的次方 1 2 4 8 16
this.threshold = tableSizeFor(initialCapacity);
}
// 其实用的就是上面的构造方法
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//默认构造方法
//注意默认构造方法没有指定初始大小
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//构造一个具有与指定Map相同的映射关系的新HashMap。 使用默认的负载因子(0.75)和足以容纳指定Map中的映射的初始容量创建HashMap
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
/**
* Implements Map.putAll and Map constructor
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
//返回size 没什么好说的
public int size() {
return size;
}
//是否为空
public boolean isEmpty() {
return size == 0;
}
//返回get到的元素
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) {
//tab:hashmap 的散列表
//first :桶 的头元素
//e:node
//n:table长度
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//table不为空 且桶有数据
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;
}
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
//put值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 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
*/
// hash key value
// onlyIfAbsent 如果存在key相同 插还是不插 默认插入
// evict 没用到
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
// tab: 引用当前hashmap的散列表
// p:当前的散列表的元素
// n:散列表数组的长度
// i:表示路由寻址的结果
//创建表
//why? new map 但是不放数据 所以在put时才创建表
//延迟初始化逻辑 第一次调用putVal时会初始化hashMap对象中最耗费内存的散列表
if ((tab = table) == null || (n = tab.length) == 0)
//真正创建表
n = (tab = resize()).length;
//最简单的情况 : 寻址找到的桶位 为 null k,v-> node 扔进去就可以了
//路由算法 (n - 1) & hash]
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//e:node临时元素 不为null的话,找到一个与当前要插入的key-value一致的key的元素
//k:临时的一个key
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);
//链表 链表头元素与我们插入 key不同
// 一个又一个比较
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;
}
}
//次数+1 修改不计数
++modCount;
//扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* 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
*
* 为什么需要扩容? 为了解决哈希冲突导致的链化 影响查询效率的问题
* 查找效率 O(n)-》O(1)
*/
final Node<K,V>[] resize() {
// oldTab 扩容之前的哈希表
Node<K,V>[] oldTab = table;
// oldCap 扩容之前的哈希表的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// oldThr 扩容之前的阈值
int oldThr = threshold;
// new 扩容之后的 。。。
int newCap, newThr = 0;
//已经初始化了 正常扩容
if (oldCap > 0) {
//没法扩容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 一倍 假如指定大小为 8 < 16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// oldCap == 0
// 1. new HashMap(initCap,loadFactor)
// 2. new HashMap(intiCap)
// 3. new HashMap(map) map有数据
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap == 0 空参构造方法
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; //16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
}
// 1.正常扩容的时候 oldCap没有大于16
// 2.没有初始化table 初始化用的 else if里面的 并没有设置 newThr
// 计算
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]; //???为什么加上 (Node<K,V>[]) 强转
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//桶位有数据 单个数据/链表/红黑树
if ((e = oldTab[j]) != null) {
//GC
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;
// 0 -> 低位
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;
}
//
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
//移除key
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
//具体remove实现
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
//tab 引用当前hashmap中的散列表
//
Node<K,V>[] tab; Node<K,V> p; int n, index;
//table 空? node是不是空
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;
//链表 or 树
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);
}
}
// 删除 是不是value也要判断
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;
}
//清空哈希表
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = 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) {
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;
}
// Overrides of JDK8 Map extension methods
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
}
这里说一下 其中一个对我来说迷惑的代码:
e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))
方法里面有很多类似这样的判断 ,为什么要判断hash值 然后还判断值是否相等,一开始我认为只用判断一个就够了。
因为 hash相等 key并不一定相等, key相等,hash也不一定相等。
比如:
public void test(){
System.out.println("ABCDEa123abc".hashCode()); // 165374702
System.out.println("ABCDFB123abc".hashCode()); // 165374702
}
2个字符串,虽然不一样,但是计算出来的hashCode是一样的,至于为什么一样,是因为hashCode方法被重写了。如下:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
//上次一算出的hash值乘以31 然后再加上当前字符编码值
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
分析:int 在java中4个字节,[-231,231-1] (注意,数学表示方法,实际java用Math.pow(2,31))
int肯定会有一个上限,当字符长时产生的数值过大int放不下时会进行截取,一旦截取HashCode的正确性就无法保证了,所以这点可以推断出HashCode存在不相同字符拥有相同HashCode。
如果这样2个字符串放入hashMap 只比较hash值,那肯定会被判断成一个对象,所以还要比较 key 也就是值是不是相同。
第二个问题就是 为什么 判断
((k = p.key) == key || (key != null && key.equals(k)))
前面的 == 其实是判断地址是否相等 ,只要不是基本类型,一般都不相等,所以后面用了 equals方法 。
我们可以重写equals方法 ,这样 在方法判断的时候,调用我们重写的方法,对象就可能相等。
4. 为什么重写equals方法需要重写hashCode方法?
网上说了半天没说到点子上,不一定要重写hashCode方法也可以判断2个对象是相等的,但是放入hashMap中,如果不重写(hashMap里面的HashCode方法计算的是地址的hash值)就会判断成2个对象。结合我上面的分析,一目了然。
ps:为什么我老是看到有博主也要重写 hashcode方法 对象才能equals判断相等 equals判断相等 其实和hashcode无关,看看源码就知道了,比如:
public class TestA {
private String name;
private Integer age;
public TestA(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TestA)) return false;
TestA testA = (TestA) o;
return Objects.equals(name, testA.name) &&
Objects.equals(age, testA.age);
}
/*@Override
public int hashCode() {
return Objects.hash(name, age);
}*/
public static void main(String[] args) {
HashMap<TestA,Integer> hashMap = new HashMap<>();
TestA test1 = new TestA("A",1);
TestA test2 = new TestA("A",1);
hashMap.put(test1,1);
hashMap.put(test2,1);
System.out.println(test1.hashCode());
System.out.println(test2.hashCode());
System.out.println(test1.equals(test2));
System.out.println(hashMap.size());
}
}
结果是 hashcode 不相等 ,但是equals是相等的,只是放入 map中会被认为2个对象
我们把重写hashcode的代码不注释
这样看起来更严谨。