HashMap

HashMap

目录

    • HashMap
    • 目录
    • 概述
    • final变量
    • 静态内部类
    • 静态工具方法
    • 成员变量
    • 构造方法
    • 成员方法
    • 迭代器
    • Spliterator
    • Summary

概述

Map是一种 key-value 格式的数据结构, key唯一。

HashMap是Java Map接口的实现类, 实现了Map接口的所有方法, 而且允许key为null, value也为null。
HashMap与HashTable基本上就是一样的, 唯一的区别就是HashTable是线程安全的, 而HashMap不是(这跟ArrayList和Vector的区别是一样的)。
HashMap不保证map的顺序, key-value pair是”随机”的存放在map中的。

HashMap_第1张图片

假定元素已经被hash函数均匀的分散在了一个个的桶(buckets)中, get()和put()的时间复杂度为O(1)。在集合上的迭代需要的时间为O(M + N), 其中M是HashMap的capacity(桶的数目), 而N是HashMap的size(key-value的数目), 所以, 如果很在乎性能的话, 那么初始的capacity就不要设置的太大咯。

如果HashMap中的元素个数超过了capacity * loadfactor, 那么整个HashMap就会rebuilt, 一般loadfactor的值是0.75。

如图所示,当多个元素经过hash()后得到了同一个hash值,那么他们会被放入一个桶内,并初始以链表的形式存储,但是当元素数目达到一定得数量之后,链表就会被”树化”(treeify)成红黑树,提高搜索的性能。

同样, 关于synchronize和fast-fail就不赘述了, 跟ArrayList, LinkedList都是相似的。


final变量

    // 所有的capacity的数值必须是2的整数次幂  
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大capacity, 2^30
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认的,loadfactor
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 一般情况下,元素的hash值如果相同,那么就依次存在一个链表里
     * 如果链表里的元素数目超过TREEIFY_THRESHOLD,就要把链表转化成一棵红黑树
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 与TREEIFY_THRESHOLD相对应,如果红黑树里的元素数目小于UNTREEIFY_THRESHOLD
     * 红黑树就退化成一个链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 这个成员变量的定义是:
     * 如果
     * 1. 一个桶里的元素个数大于TREEIFY_THRESHOLD,且
     * 2. HashTable的桶的个数大于MIN_TREEIFY_CAPACITY
     * 那么,就对桶里的元素进行"树化",否则
     * 仅仅resize整个HashTable
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

静态内部类

    /**
     * 桶里的元素(节点),含有——key, value, next
     * 所以整个桶里的元素构成了一个链表
     */
    static class Node implements Map.Entry {
        final int hash;
        final K key;
        V value;
        Node next;

        Node(int hash, K key, V value, Node 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;
        }

        // key与key相等,value与value相等,即可认为相等啦
        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;
        }
    }

静态工具方法

   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * 如果x实现了comparable接口,那么返回x的类型
     */
    static Class comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /**
     * kc是k的类型
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

    /**
     * 返回不小于cap的最小的2的整次幂
     * 比如
     * return 8 if cap = 7, 
     * return 8 if cap = 8, 
     * return 16 if cap = 9, 
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1; // 如果cap已经是2次幂整数了,这行能保证最后n不会超过cap
        // 如果n >>> 1不为0,能保证n最高非0位连续2次,即0..011xxxxxxxx
        n |= n >>> 1; 
        // 如果n >>> 2不为0,保证n最高非0位连续4次,即0..01111xxxxxx
        n |= n >>> 2; 
        // 如果n >>> 4不为0,保证n最高非0位连续8次,即0..011111111xx
        n |= n >>> 4; 
        // 如果n >>> 8不为0,保证n最高非0位连续16次,即0..0111..11xx(16个1)
        n |= n >>> 8; 
        // 如果n >>> 16不为0,保证n最高非0位连续32次,即0..0111..11xx(32个1)
        n |= n >>> 16; 
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

成员变量

    /**
     * 
     * hash表,长度总是2的幂次
     */
    transient Node[] table;

    /**
     * key-value的集合
     */
    transient Set> entrySet;

    /**
     * map里的key-value数目
     */
    transient int size;

    transient int modCount;

    /**
     * resize的门限值,超过值,就要resize了,值为(capacity * load factor)
     * The next size value at which to resize (capacity * load factor).
     */
    int threshold;

    final float loadFactor;

构造方法

    // initialCapacity会在内部做一个转换,转换成一个2次幂整数
    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);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 啥都没指定,那么capacity就是INITIAL_CAPACITY(16)以及DEFAULT_LOAD_FACTOR(0.75)
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 从一个map中构造HashMap,容量要保证容纳m的所有元素
     * loadfactor就是默认的0.75
     */
    public HashMap(Map m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

成员方法

    // 把m中的所有元素放到本HashMap中,evict参数hashMap用不着
    final void putMapEntries(Map m, boolean evict) {
        int s = m.size(); // 获取m中key-value的数目
        if (s > 0) {
            if (table == null) { // table为空,表名还没用呢
                // 用m的大小除以loadfactor得到新的capacity,注意要加1哦
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    // 更新一下门限
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                // 如果m的大小已经大于当前的门限了,就resize咯
                resize();
            // 遍历赋值
            for (Map.Entry e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                // 完成赋值,主要就是这个方法,重点关注下☆
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 通过hash和key来获取值,无需赘述啦
     */
    public V get(Object key) {
        Node e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 通过hash和key来获取值
     */
    final Node getNode(int hash, Object key) {
        Node[] tab; Node first, e; int n; K k;
        // (n - 1) & hash 这个就是桶的第一个元素的位置,也是链表的表头
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // 总是检查表头
                // key相同或者equals就返回first
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 否则,链表就往后走
            if ((e = first.next) != null) {
                // 如果链表已经被"树化"了,那么调用getTreeNode()
                if (first instanceof TreeNode)
                    return ((TreeNode)first).getTreeNode(hash, key);
                // 还是链表,那就一直next找
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    /**
     * 复用getNode(),如果返回不为空,则为包含这个key
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * 添加一对key-value,如果key已经存在了,就覆盖
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 往HashMap中插值,先查找,再插入
     * evict: 这个参数如果为true,那么每插入一个新值
     * 就把链表头"踢出去"...,保持链表元素数目不变
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; // table为空,需要"扩容"
        // (n - 1) & hash,n肯定是2的幂次方
        // 这个表达式与 hash % (n - 1) 功能一样,但是更快
        // 于是p就是桶中链表的头节点或者是桶中的树根
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 为空,说明桶里还没有元素呢,加进去即可
            tab[i] = newNode(hash, key, value, null);
        else { // 说明桶里有元素,两种情况: 要么是链表,要么是树
            Node 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)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) { // 说明新加的元素已经存在了,更新一下旧值
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    /**
     * 扩容,要保持元素顺序不变,或者是以2的整数次幂移动
     */
    final Node[] resize() {
        Node[] 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; // 旧的HashMap已经够大了,没法扩容
            }
            // capacity扩大2倍,threshold扩大2倍(if possible)
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 旧的HashMap的capacity为0
        else if (oldThr > 0) 
            newCap = oldThr;
        // 旧的capacity为0, 旧的threshold也为0,就用默认的咯
        else {               
            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属性
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node[] newTab = (Node[])new Node[newCap];
        table = newTab;
        // 旧的HashMap如果是空,直接就结束吧
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node e; // e是HashMap中一个个桶中的首元素
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null; // 原先的置空了
                    if (e.next == null) // 桶里就一个节点
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode) // 桶里的元素构成了树
                        ((TreeNode)e).split(this, newTab, j, oldCap);
                    else { // 桶里的节点构成了链表,记得要保证元素顺序
                        /**
                         * 举例说明一下即可,对于capacity为16的HashMap
                         * hash值为7和23的元素是放在一个桶里的,假设index为0和1
                         * 扩容后,长度变成了32,那么此时7和23就不在一个桶里了
                         * 7在编号为7的桶里,index为0
                         * 23在编号为23的桶里,index也为0
                         * loHead = 7[0], loTail = 7[0]
                         * hiHead = 23[0], hiTail = 23[0]
                         * 判断是Hi还是Low,拿hash值与原先的capacity(16)与一下即可
                         */
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node 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;
    }

    /**
     * 先把链表中的节点统统变成树里的节点,然后在进行treeify
     */
    final void treeifyBin(Node[] tab, int hash) {
        int n, index; Node e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode hd = null, tl = null;
            do {
                TreeNode 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);
        }
    }

    // 这个方法会替换掉已经存在的key-value
    public void putAll(Map m) {
        putMapEntries(m, true);
    }

    public V remove(Object key) {
        Node e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
    // 先查找,再删除
    final Node removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node[] tab; Node p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

    public void clear() {
        Node[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

    // 找的好辛苦
    public boolean containsValue(Object value) {
        Node[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

    /**     
     * 返回Map中的所有key的集合
     */
    public Set keySet() {
        Set ks;
        return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
    }

    // 由此也可以窥探到Set和Map的关系--Set就是Map,只不过没有用Map里的Value,把key当成Value
    final class KeySet extends AbstractSet {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumersuper K> action) {
            Node[] 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 (Node e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    /**    
     * 返回Map中的全部values集合 
     */
    public Collection values() {
        Collection vs;
        return (vs = values) == null ? (values = new Values()) : vs;
    }
    // 注意到Values没有remove()方法,因为没有key,没法删
    final class Values extends AbstractCollection {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumersuper V> action) {
            Node[] 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 (Node e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * 返回Entry的集合,一个Entry是一个key-value的封装
     */
    public Set> entrySet() {
        Set> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry) o;
            Object key = e.getKey();
            Node 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> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumersuper Map.Entry> action) {
            Node[] 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 (Node e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    // JDK8的方法

    // 跟Python的get(para, default)是一样的
    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Node e; V v;
        if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

    @Override
    public V replace(K key, V value) {
        Node e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

    // 如果key对应的元素不存在,那么就用mappingFunction算出一个value,插入Map
    @Override
    public V computeIfAbsent(K key,
                             Functionsuper K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node[] tab; Node first; int n, i;
        int binCount = 0;
        TreeNode t = null;
        Node old = null;
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode)first).getTreeNode(hash, key);
            else {
                Node e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            V oldValue;
            // 如果元素存在,且元素的value不为空,啥也不干
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
        V v = mappingFunction.apply(key);
        if (v == null) { // 算出一个null出来
            return null;
        } else if (old != null) { // 元素的value为空,更新,返回
            old.value = v;
            afterNodeAccess(old);
            return v;
        }
        // v != null, old == null,且桶里的元素都是树节点,放在书中
        else if (t != null) 
            t.putTreeVal(this, tab, hash, key, v);
        else { // 放在链表中
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1) // 正好到了"树化"的数目...
                treeifyBin(tab, hash);
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return v;
    }

    // key和value都不为空,再由一个有两个参数的函数映射成新的value,更新
    public V computeIfPresent(K key,
                              BiFunctionsuper K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        Node e; V oldValue;
        int hash = hash(key);
        if ((e = getNode(hash, key)) != null &&
            (oldValue = e.value) != null) {
            V v = remappingFunction.apply(key, oldValue);
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            }
            else
                removeNode(hash, key, null, false, true);
        }
        return null;
    }

    /**
     * 如果key对应的元素old存在,根据remappingFunction(key, oldVal)映射出来的newVal
     *     1. 如果不为空,更新old的oldVal为newVal
     *     2. 为空,删除old节点
     * 如果old不存在,且newVal不为空
     *     1. old的hash值所在的桶里的元素为树节点,那么新建节点,插入tree中
     *     2. 否则就插入到链表中
     * 否则,就返回null吧
     */
    @Override
    public V compute(K key,
                     BiFunctionsuper K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node[] tab; Node first; int n, i;
        int binCount = 0;
        TreeNode t = null;
        Node old = null;
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode)first).getTreeNode(hash, key);
            else {
                Node e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        V oldValue = (old == null) ? null : old.value;
        V v = remappingFunction.apply(key, oldValue);
        if (old != null) {
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
        }
        else if (v != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, v);
            else {
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return v;
    }

    // 跟compute差不多,只不过新加了一个value参数
    @Override
    public V merge(K key, V value,
                   BiFunctionsuper V, ? super V, ? extends V> remappingFunction) {
        if (value == null)
            throw new NullPointerException();
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node[] tab; Node first; int n, i;
        int binCount = 0;
        TreeNode t = null;
        Node old = null;
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode)first).getTreeNode(hash, key);
            else {
                Node e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        if (old != null) {
            V v;
            if (old.value != null)
                v = remappingFunction.apply(old.value, value);
            else
                v = value;
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
            return v;
        }
        if (value != null) {
            if (t != null)
                t.putTreeVal(this, tab, hash, key, value);
            else {
                tab[i] = newNode(hash, key, value, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return value;
    }

    @Override
    public void forEach(BiConsumersuper K, ? super V> action) {
        Node[] 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 (Node e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    // 把元素的value替换成一个function(key, value)的输出值
    @Override
    public void replaceAll(BiFunctionsuper K, ? super V, ? extends V> function) {
        Node[] tab;
        if (function == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node e = tab[i]; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    /* ------------------------------------------------------------ */
    // 下一是浅拷贝和序列化的操作...
    // Cloning and serialization

    /**
     * Returns a shallow copy of this HashMap instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap result;
        try {
            result = (HashMap)super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

    // These methods are also used when serializing HashSets
    final float loadFactor() { return loadFactor; }
    final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }

    /**
     * Save the state of the HashMap instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The capacity of the HashMap (the length of the
     *             bucket array) is emitted (int), followed by the
     *             size (an int, the number of key-value
     *             mappings), followed by the key (Object) and value (Object)
     *             for each key-value mapping.  The key-value mappings are
     *             emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }

    /**
     * Reconstitute the {@code HashMap} instance from a stream (i.e.,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        s.readInt();                // Read and ignore number of buckets
        int mappings = s.readInt(); // Read number of mappings (size)
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                             mappings);
        else if (mappings > 0) { // (if zero, use defaults)
            // Size the table using given load factor only if within
            // range of 0.25...4.0
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            float fc = (float)mappings / lf + 1.0f;
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                       DEFAULT_INITIAL_CAPACITY :
                       (fc >= MAXIMUM_CAPACITY) ?
                       MAXIMUM_CAPACITY :
                       tableSizeFor((int)fc));
            float ft = (float)cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                         (int)ft : Integer.MAX_VALUE);
            @SuppressWarnings({"rawtypes","unchecked"})
                Node[] tab = (Node[])new Node[cap];
            table = tab;

            // Read the keys and values, and put the mappings in the HashMap
            for (int i = 0; i < mappings; i++) {
                @SuppressWarnings("unchecked")
                    K key = (K) s.readObject();
                @SuppressWarnings("unchecked")
                    V value = (V) s.readObject();
                putVal(hash(key), key, value, false, false);
            }
        }
    }

迭代器

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

        HashIterator() {
            expectedModCount = modCount;
            Node[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { 指向第一个entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

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

        final Node nextNode() {
            Node[] t;
            Node e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            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 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 KeyIterator extends HashIterator
        implements Iterator {
        public final K next() { return nextNode().key; }
    }

    final class ValueIterator extends HashIterator
        implements Iterator {
        public final V next() { return nextNode().value; }
    }

    final class EntryIterator extends HashIterator
        implements Iterator> {
        public final Map.Entry next() { return nextNode(); }
    }

Spliterator

基本上桶ArrayList和LinkedList的用法是一样的,一个研究好了,一劳永逸


    static class HashMapSpliterator {
        final HashMap map;
        Node current;          // current node
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks

        HashMapSpliterator(HashMap m, int origin,
                           int fence, int est,
                           int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                HashMap m = map;
                est = m.size;
                expectedModCount = m.modCount;
                Node[] tab = m.table;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    static final class KeySpliterator
        extends HashMapSpliterator
        implements Spliterator {
        KeySpliterator(HashMap m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public KeySpliterator trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
                                        expectedModCount);
        }

        public void forEachRemaining(Consumersuper K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap m = map;
            Node[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.key);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumersuper K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        K k = current.key;
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator
        extends HashMapSpliterator
        implements Spliterator {
        ValueSpliterator(HashMap m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        public void forEachRemaining(Consumersuper V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap m = map;
            Node[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.value);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumersuper V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        V v = current.value;
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator
        extends HashMapSpliterator
        implements Spliterator> {
        EntrySpliterator(HashMap m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        public void forEachRemaining(Consumersuper Map.Entry> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap m = map;
            Node[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumersuper Map.Entry> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        Node e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    /* ------------------------------ */
    /** 
     * 在后面就是一些红黑树的操作...
     * /    

Summary

  • hash值与(length - 1)的与(&)操作之后,其实功能与(hash % n - 1)的作用是一样的,但是更快

    • 如果桶里有多个元素,那么这个位置就是整个链表的表头。
    • 如果桶中元素个数超过TREEIFY_THRESHOLD,那么链表就会”树化”为红黑树
  • HashMap查找操作
    HashMap中元素的查找,遵循以下步骤:

    • 先根据key得到hash值hash(key -> hash)
    • 再根据hash得到HashMap中桶的位置,也就是相同hash值对应的首个节点(hash -> first)
    • 判断key与first是否相等(必要的时候也会判断值是否相等)
      • 相等,则返回,否则
      • 判断first是不是TreeNode,是,则转化为在树中查找元素;否则
      • 桶里的元素肯定构成了一个链表,按照链表的方式查找即可
    • 查找成功,返回节点,否则,返回null。
  • HashMap中桶的元素超过一定数目之后会转化成 树!!! 比较复杂,有精力可以看看。

转载于:https://www.cnblogs.com/1202zhyl/p/5726873.html

你可能感兴趣的:(HashMap)