HashMap

236 阅读5分钟

介绍

基于Hash table 实现了Map接口。key,value可以为null。存储的数据没有顺序。

注意点

  • 假设hash分散很好,HashMap可以提供稳定的get,put操作。注意设置合适的容量capacity。如果过大,遍历操作会很耗时。
  • 因为基于hash表,可以知道影响他的操作性能的主要有两个方面:table的容量和负载。
  • 容量会影响rehash次数,负载会影响操作hash table的效率
  • 如果一张hash 表中,多个key含有相同的hashCode,将影响操作性能。在此种情况下,若keys是Comparable的,将进行比较动作。
  • 所有操作不是同步的,使用时需要使用者注意同步。使用synchronize或者Collection
  • 迭代器里面任何操作hashmap的方法的验错机制是fail-fast的。迭代的时候,只要数据结构发生改变,会抛出ConcurrentModificationException。

阅读

了解HashMap的基础是哈希表。我们这里从这几方面去了解HashMap:Map.Entry/HashIterator(EntrySet)/get.put

Map.Entry

概念:A map entry(key-value pair)。Map的存储单位

注意点:

  • 想要获取Entry的引用去做接下来的操作,只有 通过Map.entrySet返回a collection-view of the map,然后获取这个collection的iterator,最后通过iterator获取Map.Entry
  • 在iterator的时候,map若发生任何modification包括改变Entry(除非通过Entry.setValue),将发生未知行为。

HashIterator(EntrySet)

Map未实现Iterable接口,HashIterator赋予它Iterator的能力。同样Map未实现Collection接口,EntrySet赋予它Collection的部分能力(add addAll的能力就未被赋予)。

abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            //先迭代链表,再迭代table   这里是重点!!!
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            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;
        }
    }

代码逻辑不是很复杂,如果再加上语言描述反而复杂化了。重点是阅读完以后,脑袋中要有以下结论:

  • Iterator初始化:找到table中第一个不是null的Node并用next指向它,index标记下一个slot的位置。
  • 遍历的时候,顺序是slot里面的链表到下一个slot

这一段本质上就是Iterable(EntrySet),Iterator(HashIterator)的实现。

get

 public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    /**
    * 这里,散列函数的一种特殊场景的实现。hashcode的高16位与低16位异或
    */
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

hash散列函数里面没有直接使用key的hashcode,这是为什么呢?基于一种具体场景的优化。具体看HashMap的hash()。这个是对计算hash值减少冲突的一种具体场景的具体解决方案。

接下来,我们看getNode的具体操作

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) {
            // 这里注意first的获取。定位是通过(n-1)&hash,他的实际作用和取余一样(条件是n为2的幂)
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //否则,这个slot里面的数据,要么是tree或者就是链表
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    // 遍历tree
                    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;
    }

由于并不涉及并发,以上就是纯粹的逻辑代码,浏览下就可以了。

put

    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)
            // 扩容:初始化或者翻倍size
            n = (tabresize()).length = ;
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 若slot为空,则创建Node。Node包含hash(key的hashcode返回的值的高16和低16位异或计算出的hash值)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 注意到Node的类型,普通Node或者TreeNode
            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;
    }

其实还是些逻辑,没有写太多文字注释。 除了文字注释的地方,再提出几个有内容的点

  • resize() 扩容。除了size,里面还有一个技术点:每一个槽位上的链表(Node,TreeNode)的重hash。(每次扩容,槽位上的Node:注意不是TreeNode,会拆分为两个链表,一个原slot,另一个是原slot的位置加上oldCap)
  • TreeNode,Node相互转换的时机。对于Node转换TreeNode的条件就是:binCount >= TREEIFY_THRESHOLD - 1。显示把Node节点加上去再去做判断是否转换。