[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,"");
原文地址:https://www.cnblogs.com/lyhc/p/9443628.html