HashMap的数据结构是数组加链表,基于哈希表的Map的实现,Map中有一个内部类Entry封装了key和value,在HashMap中数组中元素的存在形式是Node(实现Entry),每一个Node中包含key,value和next,其中next作为链表的指针指向下一个Node,链表长度不能超过8,一旦超过就会转换为红黑树TreeNode,利用红黑树快速增删改查的特点提高HashMap的性能,HashMap中的初始容量为16,负载因子是0.75f,当集合中容量超过16*0.75=12时,将会被扩容resize(),扩大至原来的两倍即为32。
HashMap并不是线程安全的,若要实现其线程安全有3中方法
1,使用HashTable代替HashMap
2,利用Collections中synchronizedMap方法包装一下Map
3,使用ConcurrentHashMap,使用分段锁实现线程安全
HashMap的常量
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
//HashMap中的常量
//默认初始容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//一个Node中最大链表的个数,超过8则将链表转为红黑树,优化查找效率
static final int TREEIFY_THRESHOLD = 8;
//执行resize(),当bin的数量小于6时,使用链表代替树
static final int UNTREEIFY_THRESHOLD = 6;
//当桶中的bin被树化时最小的hash表容量
static final int MIN_TREEIFY_CAPACITY = 64;
----------
/**顺便说一下transient的用法,
1,,被transient修饰的变量不再是对象的持久化的一部分
2,只能修饰变量,而不能修饰方法和类,也不能修饰本地方法
3,被transient修饰的变量都不能再序列化Serializable,静态变量不管有没有
被transient修饰都不能被序列化
*/
transient Node<K,V>[] table;//带有Node的数组
transient Set<Map.Entry<K,V>> entrySet;//泛型为Entry的Set集合
transient int size;//map集合的大小(key-value)
transient int modCount;//HashMap集合被修改的次数
int threshold;//临界值
final float loadFactor;//hash表的负载因子
HashMap中resize,扩容机制
final Node<K,V>[] resize() {
//table是原来的数组(初始容量为16,负载因子是0.75f)
Node<K,V>[] oldTab = table;
//判断原来数据容量,oldCap不是为0就是大于0,会有以下判断
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//threshold的值为capacity * load factor,临界值16*0.75=12
int oldThr = threshold;
int newCap, newThr = 0;
//当oldCap>0
if (oldCap > 0) {
//MAXIMUM_CAPACITY = 1 << 30,若原数组容量已经是最大值了,
//将integer的最大值赋给临界值,返回
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//相反的情况,将oldCap左移一位即扩大一倍继续与最大值判断,
//并且原数组要大于DEFAULT_INITIAL_CAPACITY = 1 << 4;
// aka 16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY
&& oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//当oldCap==0时,即为第一次初始化表
// initial capacity was placed in threshold
//将这个临界值赋给newCap
newCap = oldThr;
//正常初始化代码
else { // zero initial threshold signifies
// using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//16
newThr = (int)(DEFAULT_LOAD_FACTOR *
DEFAULT_INITIAL_CAPACITY);//16*0.75=12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
&& ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//创建扩容后的数组,容量为newCap
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)
//若e的下一个节点为null,则将这个e作为新数组的临界值,
//这里用了一个hash算法计算新数组的临界值e.hash & (newCap - 1)
newTab[e.hash & (newCap - 1)] = e;
//判断e是否变成了树(当一个Node中的链表长度超过8时,
//会将链表转换为红黑树结构TreeNode).优化查找效率
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
/**把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与
原先相同[原先位置j],hi串的新索引位置为[原先位置j+oldCap];链表的键值对
加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),
因为capacity是2的幂,所以oldCap为10...0的二进制形式,
若判断条件为真,意味着oldCap为1的那位对应的hash位为0,
对新索引的计算没有影响(新索引=hash&(newCap-1),newCap=oldCap<<2);
若判断条件为假,则 oldCap为1的那位对应的hash位为1,
即新索引=hash&(newCap-1)= hash&( (oldCap<<2)- 1),
相当于多了10...0,即oldCap*/
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//注意这里不是e.hash&(oldCap-1),、(e.hash & oldCap) 得到的是
//元素的在数组中的位置是否需要移动
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不为null则放在新表原来的位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
//若hiTail不为null,则放在新表j+oldCap的位置上,
//这里的oldCap原数组的length
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
以下引用http://blog.csdn.net/u013494765/article/details/77837338
(e.hash & oldCap) 得到的是 元素的在数组中的位置是否需要移动,示例如下
示例1:
e.hash=10 0000 1010
oldCap=16 0001 0000
& =10 0000 0000 比较高位的第一位 0
结论:元素位置在扩容后数组中的位置没有发生改变
示例2:
e.hash=17 0001 0001
oldCap=16 0001 0000
& =1 0001 0000 比较高位的第一位 1
结论:元素位置在扩容后数组中的位置发生了改变,
新的下标位置是原下标位置+原数组长度
(e.hash & (oldCap-1))得到的是下标位置,示例如下
e.hash=10 0000 1010
oldCap-1=15 0000 1111
& =10 0000 1010
e.hash=17 0001 0001
oldCap-1=15 0000 1111
& =1 0000 0001
新下标位置
e.hash=17 0001 0001
newCap-1=31 0001 1111 newCap=32
& =17 0001 0001 1+oldCap = 1+16
元素在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit,
因此新的index就会发生这样的变化:
0000 0001->0001 0001
HashMap中的put方法
put()方法中包含了HashMap是以怎样的规则将元素添加到哈希表中的,让人眼前一亮的hash算法,hash & (table.length-1)得出下标位置。当传入一个key值会先根据hash()得出key的hashCode值,再利用hash & (table.length-1)计算该元素在数组中下标位置,若存在则根据这条链最后的next插入,如不存在判断是否需要扩容,增加新的数组元素Node
//put方法实际上执行的是putVal方法,只需要将value放入集合,而key会根据hashCode()计算出来
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
*/
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;
//这里i = (n - 1) & hash是作为index的计算方法
if ((p = tab[i = (n - 1) & hash]) == null)
//若table的i = (n - 1) & hash值为null,也就是第一个节点为空
//,则新建一个Node插入该位置
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//判断是否存在相同的key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//若存在直接将p的值覆盖,map中的key无序不重复
e = p;
//判断table[i]是否为红黑树
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) {
//新建一个Node插入
p.next = newNode(hash, key, value, null);
//判断这条链表上的数良是否超过8
if (binCount >= TREEIFY_THRESHOLD - 1)
// -1 for 1st
//转换为红黑树插入
treeifyBin(tab, hash);
break;
}
//若没有判断key值覆盖value
if (e.hash == hash &&
(key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
//onlyIfAbsent表示存在key相同时不做覆盖处理,
//或者oldValue为null时,进行覆盖操作。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);//在这里无意义,
//用于linkedHashMap的尾部操作
return oldValue;
}
}
++modCount;
//判断这个集合的容量是否大于临界值,若大于则扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);//在这里无意义,
//用于linkedListHashMap的尾部操作
return null;
}
网上盗图,一目了然
HashMap中的get方法
根据HashMap中的数据结构,可以推算出get()方法的原理,首先是根据key的hash&(length-1)计算得出数组下标找到对应的数组元素,然后遍历链表再根据equals()方法比较值和哈希值找到对应的Node,将value值返回
public V get(Object key) {
Node<K,V> e;
//get方法其实是根据key值获取到value值,最重要的是获得相应的Node
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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) {
//判断链表中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).getTreeNode(hash, key);
//找到对应的index在数组的位置后迭代链表
do {
//还是根据equals()方法判断key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}