• [java]创建一个默认TreeMap() key为什么不能为null


     本文版权归 远方的风lyh和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作。

    先看一下 TreeMap 的 put(K key, V value)

    public TreeMap() {
    comparator = null;
    }

    public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); }

     再看看 compare(key, key)这个方法

    final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }

     如果我们创建一个默认TreeMap() 如下 会报空指针异常  

      SortedMap map  =  new TreeMap<>();
      //在 上面的compare(key, key) 的方法中  红色 即为 null.compareTo(null) 程序抛出  java.lang.NullPointerException
      map.put(null,"");
  • 相关阅读:
    volatile关键字,使一个变量在多个线程间可见。
    grep sed awk
    mysql高级聚合
    Hive高级聚合GROUPING SETS,ROLLUP以及CUBE
    用SecureCRT来上传和下载文件
    mysql导出导入数据
    redis入门
    spark 常用技巧总结2
    生成数据库字典
    spark 常用技巧总结
  • 原文地址:https://www.cnblogs.com/lyhc/p/9443628.html
Copyright © 2020-2023  润新知