zoukankan      html  css  js  c++  java
  • Map 的putAll方法

    如下段代码:

    public static void main(String[] args){
    Map
    <String,String> map1 = new HashMap<>(); Map<String,String> map2 = null; map1.putAll(map2); }

    以上写法是错误的。

    hashMap的putAll方法源码如下:

    /**
         * Implements Map.putAll and Map constructor
         *
         * @param m the map
         * @param evict false when initially constructing this map, else
         * true (relayed to method afterNodeInsertion).
         */
        final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
            int s = m.size();
            if (s > 0) {
                if (table == null) { // pre-size
                    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)
                    resize();
                for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                    K key = e.getKey();
                    V value = e.getValue();
                    putVal(hash(key), key, value, false, evict);
                }
            }
        }

    调用putAll方法时会 检查参数map的size;该方法未对参数做非null判断

  • 相关阅读:
    12_常用类
    MyBatis_02 框架
    MyBatis_01 框架
    正则表达式
    11_异常处理
    产品经理成长之路(非原创)
    【Java每日一题】20161115
    【Java每日一题】20161114
    【Java每日一题】20161111
    【Java每日一题】20161110
  • 原文地址:https://www.cnblogs.com/zhaiyt/p/9815317.html
Copyright © 2011-2022 走看看