深入理解Java集合和Map 4:Map接口实现类HashMap,源码剖析及其特性。
Map
Map不属于集合类子接口,其与Collection接口是同级别关系。
HashMap
- 首先介绍两个常用的构造函数,如下,可见我们可以自定义初始容量或不指定,DEFAULT_LOAD_FACTOR=0.75常量表示的是默认扩容的一个数值,该数值介绍:假设我们HashMap初始容量为16,那么扩容的阈值容量为16*DEFAULT_LOAD_FACTOR=12,当HashMap的key-value已经有了12个时,JDK将会自动对HashMap进行扩容。扩容方法下文讲解。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 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
}
- 非线程安全。
- HashMap底层结构为数组+链表+红黑树,当存在hash值一致,并且对应位置已经有元素且待加入元素与之不同时,将会使用链表将要加入元素链接至原元素后面,需注意,在链表长度超过8时,且数组长度超过64时,将会把链表转变至红黑树结构。
- 以put()方法剖析源码及个人理解如下方代码,因涉及方法众多,附近找不到的方法请在下方仔细查看,主要集中在数组和链表部分,红黑树部分在学习树结构中详解
- 在下方1.2.1处语句说明了,即使hash值一样,内容一样,我们仍然可以重写key的equal方法来使语句不进入1.2.1中达到内容一致也可加入hashMap的问题。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {//该函数获得key得哈希值,null得hash为0
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
static final int TREEIFY_THRESHOLD = 8;
transient Node<K,V>[] table;//table为Node类数组,后文将Node得对象统一称之为节点。
//该数组即为上文描述中“HashMap底层结构为数组+链表+红黑树”得数组。
static class Node<K,V> implements Map.Entry<K,V> {
//Node静态内部类,传入进来的key-value都将被该类封装成统一形式。其主要有四个成员
final int hash;//key得hash值
final K key;//key
V value;//value
Node<K,V> next;//若形成了链表,next则是当前节点的下一个节点
}
/**
* Implements Map.put and related method
* @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)//1、此语句判断存储节点得数组是否存在
//本质上是第一次存储数据的一个初始化,将存储节点的数组创建出来
n = (tab = resize()).length;//resize方法后面有介绍
if ((p = tab[i = (n - 1) & hash]) == null)//1.1:n-1为当前数组最大下标,与hash按位与保证了所得数字不会超过最大下标,
//即key都可以落在数组中,一些其他算也有的采用hash/最大下标取余数,如果数组与后的位置为空,表明此处没有节点,直接填入,如果已经有节点,进入else
tab[i] = newNode(hash, key, value, null);
else {//1.2
Node<K,V> e; K k;//e是一个辅助节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//1.2.1:如果待加入节点与该位置已存在节点hash值相等并且key值相等且不为空,
//将已存在节点p赋给e,其实此处相当于不处理待带加入节点,直接丢弃了待加入节点,后文中会发现其实并未真正的丢弃,而是value值覆盖了旧的已存在节点value值,如果不丢弃,进入1.2.2或者1.2.3
e = p;
else if (p instanceof TreeNode)//1.2.2:如果原有节点是一个树节点,说明此处已经链接了一棵树,将待加入key-value加入树中
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//1.2.3:如果进入该处,说明原有节点是一个链表节点,后续操作应该是将新信息加入到链表尾
for (int binCount = 0; ; ++binCount) {//此循环为遍历链表,直到最后一个,将新节点加入到链表尾部
if ((e = p.next) == null) {//1.2.3.1加入链表
p.next = newNode(hash, key, value, null);//链接在尾部
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st static final int TREEIFY_THRESHOLD = 8;
//1.2.3.1.1加入后若链表长度>=8,treeifyBin进行树化并退出遍历,实际上此处即使调用treeifyBin也不一定进行树化,详见treeifyBin方法
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))//1.2.3.2:如果不进行树化则此处在加入链表后必然进入该处然后退出
break;
p = e;
}
}
if (e != null) { // existing mapping for key//1.2.4:e != null说明上面条件语句进入了1.2.1,因为进入1.2.2和1.2.3中e被赋值null
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;//返回不为空说明原来表中存在相同的key,则覆盖原来的value并返回旧的value
}
}
++modCount;
if (++size > threshold)//判断数组中节点个数是否大于threshold,threshold=数组容量*0.75,如果成立,则进行数组扩容。
resize();
afterNodeInsertion(evict);//空方法,HashMap子类可以实现
return null;//此处表示put成功
}
- 扩容函数,下文代码即注释介绍了其扩容机制,这也表明hashMap元素不仅是无序的,而且元素顺序还会随时改表
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
* @return the table
*/
final Node<K,V>[] resize() {//HashMap的数组扩容函数,主要是一些扩容逻辑,主要修改两个值:数组容量和threshold,需要注意数组扩容以二倍方式扩容,语句见下面一处汉字注释
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)//此处新容量为旧容量左移一位,即newCap = oldCap*(2的1次方)
newThr = oldThr << 1; // double threshold同时更新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;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
//此方法为树中方法,在此只说明一处,见下文汉字注释部分
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//MIN_TREEIFY_CAPACITY为64,说明在HashMap中的数组长度在小于64的时候,
//即使链表长度>=8也不会树化
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
- HashMap的get(key)方法源码剖析及个人详解见下方代码及注释,由上文中描述的HashMap的结构可查找猜测思路:1.根据key的哈希值查找在数组中的位置,如果不为空,是一个数组节点,直接返回该节点;2.是一个链表的话,输入的key依次比较链表中节点的key值,匹配上返回该节点;3.如果是树节点,则在树中查找。下方代码注释123表示上述123所描述的内容。
public V get(Object key) {
Node<K,V> e;
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) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))//对应上文1.,由于数组中节点与链表中节点是一个类型,所以直接用头节点表示即可
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)//3.是树节点,则在树中查找
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;
}
- HashMap的遍历方法众多,如下示例三种:
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("aaa", 1);
map.put("bbb", 2);
map.put("ccc", 3);
map.put("ddd", 4);
//1。map.entrySet(),推荐
for(Entry<String, Integer> entry: map.entrySet())
System.out.println(entry.getKey()+","+entry.getValue());
//map.entrySet()返回为Set集合,集合均实现了迭代器接口,所以可以使用迭代器
Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Integer> entry = (Entry<String, Integer>) iterator.next();
System.out.println(entry.getKey()+","+entry.getValue());
}
//map.keySet()
for (String key : map.keySet()) {
System.out.println(key+","+map.get(key));
}
}