hashmap的介绍:
在hashmap中,有个内置对象node,保存着索引的值key,存储的值value,key的hash值,以及节点
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; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
因此hashmap实际的存储是在一个node对象的数组table上操作的
transient Node<K,V>[] table;
初始化一个空的hashmap,有三种方法
//初始化时可以带上初始化容量,加载因子 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); // 临界值设为2的n次幂,实际上在resize操作中,会用这个值设置为table的容量大小,并将它设为容量大小*加载因子 } // 初始化时带上加载因子 public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } // 默认初始化 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // 加载因子默认为0.75 }
将容量调整为比原来容量大,2的^n次幂
/** * Returns a power of two size for the given target capacity. */ //加入cap为1001,则n为1000,m为n>>>1=100,若n|=m,则n=1100;这时m=11,n|=m即n=1111。若它小于最大值,则n=10000即2^4 static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; // 最高2位必定为1 n |= n >>> 2; // 最高4位必定为1 n |= n >>> 4; // 最高8位必定为1 n |= n >>> 8; // 最高16位必定为1 n |= n >>> 16; // 最高32位必定为1 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
这时hashmap的table还未开始初始化,它将在你存储第一个键值对时进行初始化
先简单介绍下hashmap的存储操作:hashmap先判断table是否为空,若为空,则通过resize方法,用上面初始化的值为table申请内存空间,并初始化一些参数。接着,先用key值的拿到索引,然后在table中找到索引的位置,若这个位置为空,则新建一个node节点存储在这个位置;若这个位置不为空,则发生了冲突碰撞,判断这个位置上的节点的key值是否相同,若相同,则用新值替换旧值;若不相同,则看这个节点是否是一个红黑树,若这个节点不是个树,它即为一个链表,往下查找,找到替换,未找到就插入,若这时链表长度大于等于8,则转化成红黑树;若它原先是个红黑树,则在红黑树中寻找,找到替换,未找到就插入。
// 存储操作 public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } /** * * @param hash key的hash值 * @param key * @param value * @param onlyIfAbsent 如果是true,不改变存在的值 * @param evict * @return 先前值 */ 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) // 如果tab=table为空,或者长度n=table.length为0 n = (tab = resize()).length; //resize()中会为table初始化,并返回table,计算长度 if ((p = tab[i = (n - 1) & hash]) == null) // 通过(n-1)&hash计算索引,若那个位置为空,放入一个新的node对象 tab[i] = newNode(hash, key, value, null); else { // 如果索引所在的位置,不为空,发生冲突碰撞 Node<K,V> e; K k; // 若第一个节点的key和寻找的key值相等,则节点e=当前节点 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) { // e=下个节点,若e为null,则新建个节点,当前节点执行它 p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // 若节点数为8时,链表转为红黑树 treeifyBin(tab, hash); break; } // 若这个节点e的key值和寻找的key值相等,则跳出循环 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // 如果节点e不为null V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) // 若旧的value为null,或者允许修改旧值,则将旧value替换成新value e.value = value; afterNodeAccess(e); return oldValue; // 插入发生冲突碰撞,有旧值返回旧值,无旧值返回null } } ++modCount; //修改次数++ if (++size > threshold) //如果数量大于临界值,则扩充 resize(); afterNodeInsertion(evict); return null; //插入未发生冲突,返回null }
在上面多次提到了resize这个方法,这是个重新调整table大小的方法。若table为空,为table申请内存空间。若table不为空,一般是存储的数量大于了临界值,需要重新调整table容量和临界值大小,并重新计算旧table的索引,放入新的table中。
// hashMap 重新调节大小 final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; // 旧hashmap的容量 int oldThr = threshold; //旧hashmap的临界值 int newCap, newThr = 0; //新值 if (oldCap > 0) { // hashmap不为空时 if (oldCap >= MAXIMUM_CAPACITY) { //hashmap容量为最大时,无法再resize,将临界值变为int最大,直接返回 threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) // 新的容量为2*旧的容量,如果新的容量小于最大值,并且旧的容量大于默认值,则新的临界值为2*旧的临界值 newThr = oldThr << 1; // double threshold } else if (oldThr > 0) //hashmap为空,如果旧的临界值大于0(初始化时初始化了容量,前文提到),新的容量为旧的临界值, newCap = oldThr; else { //hashmap为空,旧的临界值为0,新的容量为默认值16,新的临界值为默认容量*默认加载因子 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { //新的临界值为空时,新的容量小于最大值,且新的容量*加载因子小于最大值,则新的临界值为新的容量*加载因子,否则为Int最大值 float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } //修改临界值、buckets大小 threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) //忽略警告 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { //把每个bucket放入新的buckets中 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) //旧bucket只有一个值,则放入新的bucket中 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) //若旧bucket中放的是个红黑树 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { //若是链表 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) { //判断新增的1bit是0,还是1,若是1,则放在原处,若为0则放在索引加oldCap位置,这样能将冲突的值均匀分散到新的bucket中 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; }
解释下hash&(len-1):len=2^n为table容量大小,这其实可以理解为hash%len,但%操作效率比较低,所以采用了与操作,len-1=2^n-1,转成2进制后,有n位的1,任何数和它求与,都小于等于2^n-1。即保证了在table数组里面。同时2^n为容量大小有什么好处,因为2^n保证了这个数是偶数,减去1后为奇数,即2^n-1这个数的最低位为1,因此hash值和它求与得到的索引,即可能是奇数,也可能是偶数,若最低位是个0,则得到的索引必定是个偶数,白白浪费了一半空间,table里的奇数位都将没有值。
hashmap中根据key拿到value值
// 取值 public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; //找到node节点,则返回node节点了的value,否则返回null } /** * @param hash key的hash值 * @param key * @return 返回对应的节点或者null */ 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) { // 若table不为空,first为key值索引到的node节点 if (first.hash == hash && // 若fist不为空,则判断这个节点的key值是否符合,符合则返回当前节点 ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { // first为下个节点,若下个节点不为空 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; // table为空,或者索引到的位置不存在对应key值的node节点,返回null }
在hashmap中经常会有将另个map中的值全部存入当前的map中。
// 根据已有的map来初始化一个hashmap public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; //加载因子为默认0.75 putMapEntries(m, false); } // 将已有的map里的所有的值放到当前map中 public void putAll(Map<? extends K, ? extends V> m) { putMapEntries(m, true); } final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); //m的大小 if (s > 0) { //m不为空 if (table == null) { // 当前table为空 float ft = ((float)s / loadFactor) + 1.0F; //通过加载因子算出容量大小 int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); //判断容量大小是否大于最大值,若有,则等于最大值 if (t > threshold) // 若容量大小大于临界值 threshold = tableSizeFor(t); //重新计算临界值大小,在put过程中,会通过resize初始化,并将这个临界值当做容量大小,重新计算临界值大小 } else if (s > threshold) //当前table不为空,且容量大于临界值,重新调整table大小 resize(); for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { // 遍历每个节点 K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); //将m中每个节点的值放到当前的table中。 } } }
说完HashMap中的put和get方法,我们再去看看LinkedHashMap这个子类
static class Entry<K,V> extends HashMap.Node<K,V> { Entry<K,V> before, after; Entry(int hash, K key, V value, Node<K,V> next) { super(hash, key, value, next); } }
它实现了一个内部类Entry继承了HashMap中的内部类Node,里面多加了两个属性,befor,after,表示当前节点的上个元素和下个元素
还注意到,LinkedHashMap还增加了两个属性head ,tail,表示链表的头尾
/** * The head (eldest) of the doubly linked list. */ transient LinkedHashMap.Entry<K,V> head; /** * The tail (youngest) of the doubly linked list. */ transient LinkedHashMap.Entry<K,V> tail;
通过分析HashMap可以知道,它的put方法调用的是putVal方法,这个putVal是final类型,无法重写,因此在LinkedHashMap中,是通过重写了里面的创建Node节点方法来实现顺序
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);
看putVal方法中节选的一段代码,当通过hash计算出的索引位置,并没有元素时,创建Node元素,并赋值,看看LinkedHashMap中的实现
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { // 创建一个 LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e); linkNodeLast(p); return p; } // 构建成一个链表,举个例子 // 假设第一次是put p1,第二次put p2,第三次put p3 // 第一次 // last = null; // tail = p1; // head = p1; // // 第二次 // last = tail = p1; // tail = p2; // p2.before = last = p1; // last.after = p1.after = p2; // // 第三次 // last = tail = p2; // tail = p3; // p3.before = last = p2; // last.after = p2.after = p3; private void linkNodeLast(LinkedHashMap.Entry<K,V> p) { LinkedHashMap.Entry<K,V> last = tail; tail = p; if (last == null) head = p; else { p.before = last; last.after = p; } }
从这可以看出LinkedHashMap,还是是基于HashMap实现put和get,只是通过head,tail,和entry中的befor,after来实现顺序
在containsValue方法中,就可以看出,LinkedHashMap在寻找元素时是通过插入顺序查找的
public boolean containsValue(Object value) { for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) { V v = e.value; if (v == value || (value != null && value.equals(v))) return true; } return false; }
而在HashMap中
public boolean containsValue(Object value) { Node<K,V>[] tab; V v; if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; }
按照table这个数组,顺序查找
现在看看EntrySet这个内部类
HashMap中的实现
// 返回一个EntrySet public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new HashMap.EntrySet()) : es; } // 内部类EntrySet final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } // HashMap的entry迭代器 public final Iterator<Map.Entry<K,V>> iterator() { return new HashMap.EntryIterator(); } // 传进一个EntrySet,通过里面的key值找到HashMap的table中的node,进行对比 // Node这个对象其实实现了Map.Entry这个接口的 public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); HashMap.Node<K,V> candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } // 通过EntrySet的key、value来调用hashmap中的removeNode方法,进行移除元素 public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } // 返回分割的迭代器 public final Spliterator<Map.Entry<K,V>> spliterator() { return new HashMap.EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } // forEach循环,通过Consumer函数接口,来为每个元素执行方法 public final void forEach(Consumer<? super Map.Entry<K,V>> action) { HashMap.Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (HashMap.Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } }
清楚了HashSet中的EntrySet,来看下通过EntrySet拿到的迭代器EntryIterator
abstract class HashIterator { HashMap.Node<K,V> next; // next entry to return 下一个entry HashMap.Node<K,V> current; // current entry 当前entry int expectedModCount; // for fast-fail 表示当前的修改次数,用与快速失败策略(如果在迭代的时候,hashmap进行了插入等操作,则停止迭代,抛出错误) int index; // current slot 当前位置,默认0 HashIterator() { expectedModCount = modCount; HashMap.Node<K,V>[] t = table; current = next = null; index = 0; // next为最为table中的第一个entry if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); } } // next不为空,就说明还有entry public final boolean hasNext() { return next != null; } // 返回下个entry final HashMap.Node<K,V> nextNode() { HashMap.Node<K,V>[] t; HashMap.Node<K,V> e = next; // 快速失败策略 if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); // e为下个entry // current = e; // next = current.next // 则是next已是下下个entry,若不为null,则返回e // 如果next为null,且table如果不为null,说明这不是里不是个链表,只有一个entry,需要继续在table中寻找 if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; } // 调用hashmap中的removeNode进行移除,current置为null,并修改expectedModCount public final void remove() { HashMap.Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false); expectedModCount = modCount; } } // key值迭代器,重写next,返回key值 final class KeyIterator extends HashMap.HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } } // value值迭代器,重写next,返回key值 final class ValueIterator extends HashMap.HashIterator implements Iterator<V> { public final V next() { return nextNode().value; } } // entry值迭代器,重写next,返回key值 final class EntryIterator extends HashMap.HashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } }
然后再看看LinkedHashMap中对entrySet和entry迭代器的实现
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es; } final class LinkedEntrySet extends AbstractSet<Map.Entry<K,V>> { public final int size() { return size; } public final void clear() { LinkedHashMap.this.clear(); } public final Iterator<Map.Entry<K,V>> iterator() { return new LinkedEntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Node<K,V> candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator<Map.Entry<K,V>> spliterator() { return Spliterators.spliterator(this, Spliterator.SIZED | Spliterator.ORDERED | Spliterator.DISTINCT); } public final void forEach(Consumer<? super Map.Entry<K,V>> action) { if (action == null) throw new NullPointerException(); int mc = modCount; for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) action.accept(e); if (modCount != mc) throw new ConcurrentModificationException(); } }
LinkedHashMap中的entryset和hashmap中的没有什么不同,只是在迭代器中使用的是linkedEntryIterator
abstract class LinkedHashIterator { LinkedHashMap.Entry<K,V> next; LinkedHashMap.Entry<K,V> current; int expectedModCount; LinkedHashIterator() { next = head; // next为链表中的head expectedModCount = modCount; current = null; } public final boolean hasNext() { return next != null; } // 返回下个entry,并将next执行entry的下个元素 final LinkedHashMap.Entry<K,V> nextNode() { LinkedHashMap.Entry<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); current = e; next = e.after; return e; } public final void remove() { HashMap.Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false); expectedModCount = modCount; } } final class LinkedKeyIterator extends LinkedHashMap.LinkedHashIterator implements Iterator<K> { public final K next() { return nextNode().getKey(); } } final class LinkedValueIterator extends LinkedHashMap.LinkedHashIterator implements Iterator<V> { public final V next() { return nextNode().value; } } final class LinkedEntryIterator extends LinkedHashMap.LinkedHashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } }
通过对比可以看出,linkedEntryIterator在遍历的时候,效率上会比EntryIterator更高,不需要在table中寻找,并且具有一定的顺序
在大致分析完linkedHashMap,我们在看看accessOrder这个属性,初始化的时候默认为false
public V get(Object key) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null) return null; if (accessOrder) afterNodeAccess(e); return e.value; }
这个属性是用在当你通过get方法访问元素的时候,如果这个属性设为true,则将这个元素放在链表的最前面
void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; if (b == null) head = a; else b.after = a; if (a != null) a.before = b; else last = b; if (last == null) head = p; else { p.before = last; last.after = p; } tail = p; ++modCount; } }
总结:
1. HashMap在初始化的时候,最好给予初始容量,因为在resize的时候需要消耗性能
2. HashMap默认的负载因子为0.75,可以根据实际情况调整,减少hash冲突
3. HashMap是可以put(null,null)的
4. 想要遍历HashMap可以使用EntrySet来返回EntryIterator来进行遍历。如果想要线性的可以使用LinkedHashMap
5. 使用LinkedHashMap,在性能上会HashMap低点,因为要维持顺序。
6. HashMap并非线程安全的,因为并没有看到锁相关的操作