本文版權歸 遠方的風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,"");