JAVA集合类深入的HashMap

一些参数

默认的初始的容量

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

默认的负载因子

    static final float DEFAULT_LOAD_FACTOR = 0.75f;

链表的长度大于8就将其转为红黑树

    static final int TREEIFY_THRESHOLD = 8;

用来存储实际数据的数组

    transient Node<K,V>[] table;

一些简单的设计思想

如何放进元素

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

hash算法如下,就是调用对象自己的hashcode。

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

然后核心代码如下

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果第一次添加元素,会在这一步初始化存储数组
        //存储为Node<K,V>[] table
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //查看是否发生hash碰撞,方法是数组长度n-1和hash码的按位与。如果否则直接创建。假设你重写了key对象中的equals方法而忘记重写hashcode,此时你就要接受equals的key存在存进去多次的可能性。当然也要接受相等的key取出来的内容不同。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

        
        else {
            //这里的NODE是一个链表
            Node<K,V> e; K k;
            //检查是否已经存在这个key。此时使用的方法是equals。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //假设这个位置已经发生过很多此哈希碰撞,就把他放在一个树形结构里(红黑树,一种自平衡的二叉查找树)。TreeNode继承自LinkedHashMap里的Entry<K,V>静态内部类,而该类又继承HashMap里的Node。LinkedHashMap则是继承自HashMap。笔者完全不可理解这么设计的理由。
            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的过程如下

    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) {
            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 //扩大阈值到一倍
        }
        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;//负载因子*当前的容量得出当前的阈值,一般而言负载因子小于1
            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;
    }

如何取出

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //首先检查该hashmap是否存在
        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;
    }

序列化

hashmap里面的数组是被transient修饰的。所以,序列化的时候需要借助额外的方法。

    //这个方法虽然是private的,但是实际运行时会调用他进行序列化
    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);
    }

    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K,V>[] tab;
        if (size > 0 && (tab = table) != null) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }

复制

hashmap有clone标记接口,表示可以调用clone。clone并没有什么特别的,无非是调用父类clone,然后把自己的每一个元素放在新产生的HashMap里。@SuppressWarnings(“unchecked”)

    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)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;
    }

并发

在对象里有modCount字段,用来记录hashmap被修改次数。如果使用迭代器遍历的时候发现该值出现变化,则发生并发访问,抛出异常,快速失败。

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

实际使用的方法如下

        //初始化时把expectedModCount置为和外部类对象的modCount一致
        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();
            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;
        }
    }

你以为这样抛出个异常就完了!!!其实这个异常只是提醒作用。免的真有小白程序员不知道这个事。事实上,多线程的put(具体来说是在put引起resize的时候)会导致死循环。JDK开发者们是尽最大努力抛出这个异常,但是他们不能保证不会发生最惨烈的后果。另外,即使代码不陷入死循环,并发的put显然可能导致相同keyhash的元素在并发存储时在链表中相互覆盖。所以,千万不要在多线程中使用hashmap。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值