定义
HashMap 是一个键值对的集合,key值允许为null,key值不允许重复。value可重复,可null。
源码分析
- 内部属性
//初始大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//从链表变为红黑树的链表个数
static final int TREEIFY_THRESHOLD = 8;
//从链表变为红黑树数组最小的容量
static final int MIN_TREEIFY_CAPACITY = 64;
//hashMap中的实际存放元素的属性,同时也是个单向链表
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数组,存放元素的数组
transient Node<K,V>[] table;
//map的大小
transient int size;
//扩容的临界值
int threshold;
//负载因子
final float loadFactor;
- 构造器
HashMap 提供了4个无参构造器。其实值得一看的 只有一个。
如果看重效率,则可以设置负载因子低一点,hash碰撞概率低
如果看重内存,则可以设置负载因子高一点。
当热,也看情况吧,想详细了解,看下边的put方法的代码。
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;
//该方法为了让所有的初始大小都为2的N次方,
//也就是说 当你使用Map map = new HashMap(10,0.75f);
//他的容量并不是10 而是16 ,就是因为调用了下边这个方法。
//容量为2的N次方可以让hash值更加分散。减少hash碰撞
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 |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
- 扩容
final Node<K,V>[] resize() {
//老的table
Node<K,V>[] oldTab = table;
//老table容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//老table临界值
int oldThr = threshold;
//新table的容量,临界值
int newCap, newThr = 0;
//非首次扩容 并且 创建HashMap时没有指定大小
if (oldCap > 0) {
//如果老的table已经扩到最大,则返回原来的table
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//在判断中就扩容了两倍,如果新的容量小于最大值并且老的容量大于等于16 则新的临界值也增加2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//这种情况是,在构造器已经指定HashMap的大小
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);
}
//如果新的临界值为0.则设置
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
//创建扩容后的Node数组
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//如果oldTal中有数据,则迁移到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;
//如果该位置放置的是红黑树,//TODO(分组迁移?)
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;
//不需要重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了
//是0的话索引没变,是1的话索引变成“原索引+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.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
微信图片_20180205170215.png
- 添加 put(k,v)
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
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) {
//tab :table数组。p: 链表的第一个位置的元素。n:总容量。i:索引位置
Node<K,V>[] tab; Node<K,V> p; int n, i;
//首次添加,扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//当前索引位置上没有元素,直接放入该位置。
//在找位置的时候 hash & (n-1) 这个算法也是很厉害的。在1.7的时候还是hash % n计算得出索引位置。
//该算法效率更高。 hash & (n-1) = hash % n
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//该位置已经有元素了。
Node<K,V> e; K k;
//如果该位置的元素hashcode值相等并且通过equals也相等,则直接覆盖。
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果该元素为红黑树,则直接按红黑树处理。(在链表上超过8个则为红黑树)
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);
//如果该链表已经有8个了。则变为红黑树。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//在这里,值得一提的是,如果此时链表数量达到了8,但是容量没有达到64
//则先扩容再说,不变成二叉树
//关于红黑树(增加插入,查找的效率),等有时间了(彻底研究明白)在开篇文章。
treeifyBin(tab, hash);
break;
}
//此时,如果新添加的和该链表上的有相同的 则直接覆盖,跳出循环,
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//把新的元素变为下一个元素,继续循环判断
p = e;
}
}
//上边老说覆盖,其实这里是覆盖的代码。
//就是如果重复了。则把值赋给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;
}
//下边在借个图,关于扩容的流程.图来源(美团技术沙龙)
hashMap put方法执行流程图.png
- value get(key) 通过键值或者value值。 //如果看懂了put的流程,那么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;
//直接跳转到getNode(hash,key)方法
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;
//先做一下Node数组的非空判断,
//并且,通过hash & (n-1)获取索引位置赋值给first
//在这里,first就是该位置上链表的第一个元素。
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果第一个元素通过hash和equals判断都相等,则直接返回
//之所以第一步就这么判断,是为了效率。
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);
//不是红黑树,从链表中查询,一直next直到 hash和equals都相等。
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
- remove(key) 删除方法
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V remove(Object key) {
Node<K,V> e;
//跳转removeNode方法。
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* 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;、
//非空判断并且赋值
//p为该位置的第一个元素
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;
//定义node变量,也就是一会要删除的变量
//接下来的逻辑是找到node
//经过判断 该值就是node
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//如果第一个不是,就从该链表继续往下找
else if ((e = p.next) != null) {
//如果是红黑树,则通过getTreeNode从红黑树中查询
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//不是红黑树,一直next找到node
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//找到node后,因为matchValue为false。则肯定会进入判断
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);
//如果node==p 那么把该位置设置成node的下一个,如果是空,则为空
else if (node == p)
tab[index] = node.next;
//如果不是,则从新设置next关系
//刚开始看着个的时候有点懵。但是后来发现了。
//如果能进到下边这个判断,则p就不是第一个元素了, 而是node的上一个元素,
//因为在上边循环的时候 有这么一行代码 p = e;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
- 总的来说 JDK1.8 无论是从找索引的位置,还是扩容的机制,还是链表变红黑树都增加了效率。
1.8很不错。