美文网首页
HashMap的使用居然还有这种限制?!!

HashMap的使用居然还有这种限制?!!

作者: sha4yu0119 | 来源:发表于2019-03-19 17:14 被阅读0次

    其一

    请问, 以下几段代码的输出分别是什么?

    代码1

            Map<Map<String, String>, String> map = new HashMap<>();
            HashMap<String, String> key = new HashMap<>();
            map.put(key, "value");
            System.out.println("Before:" + map.size());
            Iterator<Map.Entry<Map<String, String>, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
            System.out.println("After:" + map.size());
    

    代码2

            Map<Map<String, String>, String> map = new HashMap<>();
            HashMap<String, String> key = new HashMap<>();
            map.put(key, "value");
            key.put("1", "2");
            System.out.println("Before:" + map.size());
            Iterator<Map.Entry<Map<String, String>, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
            System.out.println("After:" + map.size());
    

    代码3

            Map<Map<String, String>, String> map = new HashMap<>();
            HashMap<String, String> key = new HashMap<>();
            map.put(key, "value");
            key.put("1", "1");
            System.out.println("Before:" + map.size());
            Iterator<Map.Entry<Map<String, String>, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
            System.out.println("After:" + map.size());
    

    其二

    答案揭晓,输出分别是

    // 代码1
    Before:1
    After:0
    // 代码2
    Before:1
    After:1
    // 代码3
    Before:1
    After:0
    

    这是为什么呢?如果你和我一样,都感觉有些莫名其妙。那来,我们来慢慢揭晓答案。

    其三

    首先我们跟进源码找到 HashMap.entrySet().iterator() 的会返回一个 HashIterator 实例。然后定位到 remove 方法

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

    会发现他实际上会调用 HashMap::removeNode 方法。跟进该方法

        final Node<K,V> removeNode(int hash, Object key, Object value,
                                   boolean matchValue, boolean movable) {
            Node<K,V>[] tab; Node<K,V> p; int n, index;
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
                   // remove node .....
            }
            return null;
        }
    

    开启DEBUG模式,我们会发现,在代码2中,程序在执行 (p = tab[index = (n - 1) & hash]) != null时,得到的结果为null。那就说明在期望的存储位置中,没有找到对应的元素。

    那我们再来看看HashMap是如何处理新添入的元素,找到 HashMap::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)
                n = (tab = resize()).length;
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
    
             // ......... some operate......
            return something;
    }
    

    到这里,就算破案了。原来HashMap在放置元素时,是根据目标的HashCode来确定位置。在此之后,如果通过引用再对原对象进行修改,那么就会导致在 remove 时查不到该元素。

    其四

    那细心的同学可能注意到,在代码块3中,我们同样对原对象进行了修改,为何仍然能成功移除。

    这个就要涉及到HashMap的HashCode计算方式了,我们找到 HashMap的 hashCode 实现

        public int hashCode() {
            int h = 0;
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext())
                h += i.next().hashCode();
            return h;
        }
    

    这里是将集合内所有元素的hashCode累加而得。继续跟踪找到 HashMap.Node::hashCode

            public final int hashCode() {
                return Objects.hashCode(key) ^ Objects.hashCode(value);
            }
    

    可知,Node的HashCode是有key 和 value 的hashCode做异或运算而得。在我们 put("1", "1") 之后,HashMap的HashCode的仍然为0,简单来说,就是HashCode发生了碰撞。设值前后的HashCode是一样的,都为0。这个时候去Remove,当然能够成功了。

    这里不仅仅影响到 Iterator 的 remove。同样也会影响到 HashMap的remove, get 等方法。

    总结一下。HashMap的元素定位,与其Key的HashCode息息相关。在日常开发中,尽量使用不变的对象(Immuable Object)去作为Key,否则会导致对集合的读写失败。

    相关文章

      网友评论

          本文标题:HashMap的使用居然还有这种限制?!!

          本文链接:https://www.haomeiwen.com/subject/cwsnmqtx.html