HashMap作为java开发中最常用的数据结构和面试中出现频率最高的类,它的魅力到底在哪里呢。
1,构造函数:该类同样有多个构造函数,这里只看默认的构造函数
/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
使用默认的容量16和默认的加载系数0.75,但未见初始化。
2,属性定义
/** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table;
用node数组保存元素
final int hash; final K key; V value; Node<K,V> next;
node缓存了key的hash,key,value和下一级元素。这就是所谓的hash表,数组中放元素,元素中链接着下一个放进来的hash计算后下标相同的元素。换句话说,每个下标放的是一个单向的linkedList
table的注释翻译:表,在第一次使用时初始化,并根据需要调整大小。分配时,长度总是2的幂。(在某些操作中,我们也允许长度为零,以允许当前不需要的引导机制。)
3,跟ArrayList一样,也是第一次使用时初始化,看下put方法。
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
3,进入putVal。
* @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; ………… }
参数定义:
onlyIfAbsent:true则不替换原有值,fase替换,put方法传的false。
evict:true则可能移除最老未使用的元素。put方法传的true。
//663行 afterNodeInsertion(evict); //1775行 // Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { }
但未处理,实际是给子类LinkedHashMap用的方法。
返回定义:
如果为none,则返回null,可见hashmap的value可为null。
方法逻辑:
如果table是null或者table的元素个数是0,就resize();
4,进入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) { ………… } 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) { ………… } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { …… } return newTab; }
如果node数组是null,原容量就为0,原扩容阈值也取0
原容量>0?否
原阈值>0?否
else 新容量为默认容量16,新阈值为16*0.75取整12
新阈值=0?否
把新阈值赋值给对象阈值,用新容量初始化对象table。
到这里就算是完成初始化了。可见hashmap确实是非线程安全的,初始化的时机不对,比如一个线程先new了hashmap,然后两个线程同时put第一个元素,初始化完成必然会丢掉一个元素,因为都是放到自己新建的数组里。
继续往下,
如果原容量确实大于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 }
而且原容量甚至都大于等于最大容量了就修改扩容阈值为最大int,也就是不扩容,先挤一挤。
不然就2倍扩容。
既然新建了一个node数组,自然是要把原来的数据都考到新数组里面来。这里就展示了table注释里说的:分配时,长度总是2的幂,的优势了。也就是为什么长度使用2的幂以及2倍扩容。
先看hash(key)方法
/** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
如果key为null,hash取0,也就是hashmap的key可以传null,并把元素放到索引下标0的位置。
拿key的hashcode与hashcode的无符号右移16位(也就是左边16位)进行异或运算,同为0的取1。
翻译注释:
因为许多常见的散列集已经被合理地分布了(所以不能从传播中获益),而且我们使用树来处理容器中的大组冲突,所以我们只需以最廉价的方式异或一些移位的比特来减少系统损失,以及合并最高位,否则由于表边界的原因,这些位永远不会用于索引计算。
这里要注意的是,这个hash计算过程是与hashmap的table的容量是无关的,只与key有关。
放入元素时的索引下标计算
i = (n - 1) & hash; tab[i] = newNode(hash, key, value, null);
hashmap 629,630行
下标是容量减一与hash的与运算,假如容量16,减一,二进制为1111,不管hash是什么,计算结果都是hash的低四位的值。也就是说这个下标的链表上的所有元素的后四位是一样的。
扩容复制元素时
//hashmap 720行 if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; }else {} //hashmap 735行 if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; }
hashmap 720行
原容量和hash的&运算,假如由16扩容到32,原容量16,二进制为10000,计算结果由hash的第5位决定。hash的第5位要么为0,要么为1。
是0的话,与新容量32减一做&运算求下标时,结果还是hash的原低四位。11111&0xxxx为0xxxx
是1的话,与新容量32减一做&运算求下标时,结果要加上新增的1。11111&1xxxx为1xxxx,而这个1代表的是原容量的大小,也就是低四位加上16作为新下标。
所以扩容时复制的结果为:索引x处的链表分成索引x处和索引(x+16)处,两条链表。
总结:2倍扩容和容量为1*2的幂指数倍,不仅提高了插入元素时计算索引的效率,同时提高了扩容复制元素时链表分裂的效率,因为只需要判断hash的高一位的值是0还是1就能找到元素的新索引下标。
5,扩容完,回到putVal()。
a.如果索引位置不存在元素,就新增。
b.如果索引位置是红黑树节点,就插入到红黑树结构中。
c.否则找到同key的节点替换或者找到链表的末尾添加元素。
6,扩容时机,putVal()661行
if (++size > threshold) resize();
添加完元素后扩容,不是添加前,如果元素数量大于扩容阈值则扩容。
7,get逻辑:计算索引,循环比较key。
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) { 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) { 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; }
8,使用要求
a:不适用与多线程,初始化容量,put新元素,扩容都是非线程安全的。
b.key所属类应当重写equals和hashcode方法。否则使用object类的方法。如下
public boolean equals(Object obj) { return (this == obj); }
但我们实际应用中往往只需要判断某个属性,比如id,姓名,身份证,手机号等等,所以需要重写equals,重写了equals,就必须要重写hashcode方法,保证equals相等时hashcode一定相等,否则会导致equals相等的两个元素,由于hashcode不相等而放到hashmap的table的两个索引位置,也就是我们认为是同一个,但hashmap认为是不同的两个。重写方法可参考string类。