HashMap 详解
前言
众所周知,有一种数据结构可以用于快速的查找对象,那就是散列表。散列表为每一个对象计算一个叫做哈希值(Hash Code)的整数值。它是有对象的实例化字段得出的一个整数。更准确的说,有不同数据的对象将会产生不同的哈希值。
哈希值是一段数据唯一且极其紧凑的数值表示形式。
Java中String的HashCode计算
String s = "jiangyh";
System.out.println(s+"\tHashCode:"+s.hashCode());
String s1 = "JiangYH";
System.out.println(s1+"\tHashCode:"+s1.hashCode());
String s2 = "jiangyh";
System.out.println(s2+"\tHashCode:"+s2.hashCode());
字符串 | 哈希值 |
---|---|
jiangyh | -1609835382 |
JiangYH | 54816874 |
jiangyh | -1609835382 |
如果a.equals(b)==true,则a,b的哈希值一定相等。
String中hashCode方法,返回的哈希值可以为正数或者负数。
public static int hashCode(byte[] value) {
int h = 0;
int length = value.length >> 1;
for (int i = 0; i < length; i++) {
h = 31 * h + getChar(value, i);
}
return h;
}
概念
数组:数组是一种数据结构,用来存储同一类型值的集合。可通过一个整数下标进行索引,访问数组中的元素。索引数组元素时间复杂度为O(1),遍历数组时间复杂度为O(n),对于一般的插入删除操作,涉及到数组元素的移动,其平均复杂度也为O(n)。
在数组中间删除或者添加数据开销很大。这是我们更应该使用链表。
链表:将每个对象单独存放在单独的链接中,每一个链接还存在着序列中下一个链接的引用。
对于链表的新增,删除等操作(在找到指定操作位置后),仅需处理结点间的引用即可,时间复杂度为O(1),而查找操作需要遍历链表逐一进行比对,复杂度为O(n)
红黑树:红黑树是一种特化的AVL树(平衡二叉树),都是在进行插入和删除操作时通过特定操作保持二叉查找树的平衡,从而获得较高的查找性能。
哈希表:在哈希表中进行添加,删除,查找等操作,性能十分之高,不考虑哈希冲突的情况下(后面会探讨下哈希冲突的情况),仅需一次定位即可完成,时间复杂度为O(1)。
哈希表的主干就是数组。比如我们要新增或查找某个元素,我们通过把当前元素的关键字 通过某个函数映射到数组中的某个位置,通过数组下标一次定位就可完成操作。
HashMap的实现原理
HashMap 继承自AbstractMap,实现了Map、Cloneable、Serializable接口。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
HashMap是由Entry数组和链表组成。Entry是HashMap的基本组成单元,HashMap中的数组是实现了Map.Entry的Node静态类。
static class Node<K,V> implements Map.Entry<K,V>
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
所以HashMap的主体是由数组和链表组成,链表是为了解决哈希冲突。在通过哈希值查找时,如果所对应的Entry数组不含有链表,则查找和添加效率都很高。而有链表的话,则需要对链表中的对象使用equals方法进行比较,如果相等则返回对象,否则返回null。
并且由于HashMap的函数均没有synchronize关键字修饰,所以HashMap为非线性安全。
下面有几个HashMap比较重要的参数。
/**
* The default initial capacity - MUST be a power of two.
* 默认的初始化容量16 - 必须为2的幂次 10000
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
* 最大的容量值 1,073,741,826=1<<30
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 构造时默认的填充因子0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 构造红黑树的最低数量,当一个桶中的链表数超过八个并且总节点数大于MIN_TREEIFY_CAPACITY
* 则将数组加链表构造为数组加红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* 如果少于树节点少于6个时,将红黑树转为链表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
* 构造红黑树是最少的总结点个数
*/
static final int MIN_TREEIFY_CAPACITY = 64;
在JDK1.8之后将链表转化为红黑树,可以增加节点多时的增删查的效率,提高HashMap的性能。
构造方法
public HashMap(int initialCapacity, float loadFactor)
public HashMap(int initialCapacity)
public HashMap()
public HashMap(Map<? extends K, ? extends V> m)
如果用户没有传入initialCapacity、loadFactor则会使用默认的16和0.75。
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) //传入初始容量小于零,抛出异常。
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) //大于最大值时,只创建最大值容量的HashMap
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor)) //填充因子小于零或者为NaN是抛出异常。
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
此时我们可以看出,构造函数并没有对HashMap的数组分配空间,只是单纯的设置了填充因子和初始化的容量。而tableSizeFor方法是为什么初始容量一定会是2的幂的关键。
为什么initialCapacity一定为2的幂次
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 static int numberOfLeadingZeros(int i) {
if (i <= 0)
return i == 0 ? 32 : 0;
int n = 31;
if (i >= 1 << 16) { n -= 16; i >>>= 16; }
if (i >= 1 << 8) { n -= 8; i >>>= 8; }
if (i >= 1 << 4) { n -= 4; i >>>= 4; }
if (i >= 1 << 2) { n -= 2; i >>>= 2; }
return n - (i >>> 1);
}
numberOfLeadingZeros方法会返回二进制形式i的前导零的个数。
例如:
(268,435,456)= 0001 0000 0000 0000 0000 0000 0000 0000
numberOfLeadingZeros(268435456)=3
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
Integer.numberOfLeadingZeros(268,435,456-1)=4,java中>>>为逻辑右移,-1 在机器中显示为 1111 1111 1111 1111 1111 1111 1111 1111,逻辑右移高位填充0,所以右移4位后n就为 0000 1111 1111 1111 1111 1111 1111 1111=(268,435,455)。
返回时,如果n小于零返回1,否则n不超过 MAXIMUM_CAPACITY返回n+1,超过返回MAXIMUM_CAPACITY。
所以最后返回的值为268,435,456=2^28。
所以当cap值为任意整数时,通过tableSizeFor方法都可以将其变成大于cap的2的幂次方数。
put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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) //数组为空则创建存储在数组上。
tab[i] = newNode(hash, key, value, null);
else { //否则查找key,有相同的key就覆盖value,没有就新建链表节点将数据放在上面。
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);
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;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
我们可以看到在put方法中才会给数组分配空间。
首先会使用哈希值索引数组元素位置,如果元素为null则直接放到元素上。如果不为null,遍历元素和连接的链表节点,判断key是否相同,如果相同就直接覆盖value,否则新建链表节点放置数据。
最后判断填充的桶的个数是否大于阈值,大于则执行resize方法。
这里使用其他博主的图片为大家展示。
https://blog.csdn.net/woshimaxiao1/article/details/83661464
hashCode方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
如果key不为空,计算hash的方法为key的hashCode异或value的hashCode所获得值h,h在与逻辑右移16位的h进行异或运算,得到HashMap中的哈希值。
resize方法
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)
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;
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;
}
先判断*2后的cap值是否大于最大值,然后在进行扩容。
满足生成红黑树的条件就生成红黑树,不满足继续以数组+链表的形式扩容。
get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(key)) == null ? null : e.value;
}
final Node<K,V> getNode(Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != 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;
}
get方法通过key值返回对应value,如果Key为null,则返回null。
总结
- HashMap为非线性安全,并且Key、Value均可为null,由于key是唯一的,所以为null的key也只有一个。不过value为null可以不止一个。
- 通过get方法获得的value为null有两种情况,一种是key为null,另一种是value为null。因此如果要判断key是否存在,需要使用containsKey方法判断是否有该key。
- HashMap的默认初始容量为16,默认填充因子为0.75。当不为null的桶的个数大于等于16*0.75时,则进行扩容。
- 1.7之前的HashMap是由Entry数组+链表实现,先扩容后插入。1.8改为Entry数组+链表\红黑树实现,先插入后扩容。
- 在重写equals方法时,必须注意重写hashCode方法。
- 扩容时为原容量的2倍。容量一定为2的幂次方。
- 如果需要满足线程安全,可以用 Collections的synchronizedMap方法使HashMap具有线程安全的能力,或者使用ConcurrentHashMap。