介绍
HashMap是实现Map接口,是键值对的存储形式。
特点
- 存储是无序的
- 键和值位置都可以是null,但是键位置只能是一个null
- 键的位置是唯一的,底层的数据结构控制键
- JDK1.8以前的数据结构是:数组+链表,JDK1.8以后得结构是:数组+链表+红黑树
- 链表长度>8并且数组长度大于64,才将链表转换为红黑树,变为红黑树的目的是为了高效的查询
public class TestDemo1 {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("A",1);
hashMap.put("B",2);
hashMap.put("C",3);
hashMap.put("A",20);//重复put相同key的数据,后面put的value覆盖前面的value
System.out.println(hashMap);
}
}
执行过程
{A=20, B=2, C=3}
Process finished with exit code 0
存储过程
创建
当创建HashMap集合对象的时候,在JDK8以前,构造方法创建一个长度为16的数组Entry[] table用来存储键值对数据。在JDK8以后,构造方法不会创建数组,而是在HashMap对象第一次被put数据时创建数组Node[] table。这样做可以节省空间。
HashMap在创建数组时,默认容量是16,默认负载因子是0.75,默认数值size阈值是initialCapacity乘loadFactor=16*0.75=12,即zise为16的数组内存入12个数据或链表的时候,就需要扩容。HashMap在被构造时,可以传入程序员自己定义的数组容量int initialCapacity和负载因子 float loadFactor,HashMap自身会根据特定的规则结合程序员自定义的容量和负载因子,制定出新的容量和阈值。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* Returns a power of two size for the given target capacity.
* HashMap自身会根据特点的规则结合程序员自定义的容量和负载因子,制定出新的容量和阈值
*/
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
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);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
put数据
第一次put数据时会创建Node数组,默认size16。然后根据key值,调用HashMap自己提供的hash算法,计算出key对应的hash值,然后根据key的hash值再与(Node数组长度-1)做与运算,计算出当前put的数据应该放到Node数组的哪一个下标位置,把数据存放到Node数组中对应的位置,如果对应的位置没有存储数据,就直接存储,如果对应的位置已经有数据了,那么就把当前数据挂接到当前数组位置存储的链表上。
public V put(K key, V value) {//计算hash值
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; //如果数组是空的,就初始化一个数组出来
if ((p = tab[i = (n - 1) & hash]) == null) //计算出put进来的key的值对应的数组下标
tab[i] = newNode(hash, key, value, null); //生成一个Node对象,存入数组对应下标位置
else {//如果数组不是空
Node<K,V> e; K k;
if (p.hash == hash && //p是当前put进来的数据计算出的数组下标,判断当前下标的hash值是否和put进来的数据hash值是否一样,再判断传进来的key是否一致,如果一致,就把传进来的key和value覆盖掉之前的key和value
((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) {//binCount链表拥有元素
if ((e = p.next) == null) {//当前这个数组下标位置只有一个元素
p.next = newNode(hash, key, value, null);//插入put进来的数据
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st //判断这个链表要不要改成红黑树,当binCount=8时,然后判断数组size是否大于64,两者都满足,则转成红黑树,如果数组size没超过64,则只对数组进行扩容。此逻辑在treeifyBin(tab, hash)方法中实现
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;//如果key之前就存在,把传进来的key和value覆盖掉之前的key和value
if (!onlyIfAbsent || oldValue == null)//如果put的时候使用的是map.putIfAbsent()方法,则不覆盖
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
HashMap中的hash算法
如果key为null,返回0
如果不为null,先使用hashCode()方法获取到一个值,把这个值赋值给h
把h右移16位获得一个值,临时记作num,最后把 h和num做异或运算返回
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
扩容
HashMap被一直put数据,当存放的数据元素(数据或链表)超过自身容量的阈值时,就开始扩容,扩容为原来的2倍。链表中的数据会重新计算数组索引,放到对应的新的数组下标位置,直接存放或形成新的链表存储。当链表的长度达到8,且数组长度不小于64的时候,链表长度过长,影响查询效率,hashmap就需要把链表转换成红黑树存储。当数组再扩容时,红黑树中的数据和链表中的数据进行再次计算数组索引,放入新的数组下标位置。当红黑树长度小于6的时候,红黑树再次退化为链表存储
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) //如果当前需要移动的元素,没有next,即当前数组下标位置,只存了一个元素
newTab[e.hash & (newCap - 1)] = e; //直接求出对应应该存在新数组的位置,存入数据
else if (e instanceof TreeNode) //如果当前旧数组位置存了多个元素,判断存的是红黑树还是链表
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//如果存的是链表,重新计算next数据对应的数组下标
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;
}
HashMap和HashTable的区别
- HashMap可以存一个空key和多个空value,HashTable不允许存空key和空value
- HashMap计算key的hash时是使用了自己的算法,而HashTable是直接使用hashCode
- 计算数组位置索引时,HashMap是与运算,HashTable是模运算
- HashMap扩容时扩大为原来的2倍,HashTable扩容时扩大为原来的2倍+1
- HashMap线程不安全,HashTable线程安全
- HashMap是实现了Map的接口,HashTable是继承了Dictionary类