JAVA中的HashMap

首先,我们看看如何放进元素

    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;
    }

然后,我们看看如何取出

    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。

猜你喜欢

转载自blog.csdn.net/define_us/article/details/80145395