TreeMap java 实现 - 放置第一个元素

TreeMap java implementation - putting 1st element

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

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

在我的应用程序中遇到一些错误后,我不得不调试 TreeMaps put 方法。我的问题是比较放置在地图中的对象。奇怪的是,当我将 FIRST 元素放入地图时,它会与自身进行比较。我不明白为什么它会那样工作。任何见解(除了评论 "type (and possibly null) check" 之外)?他们为什么不检查密钥是否为空?那里进行了什么样的 "type" 支票,目的是什么?

我相信这是 TreeMap< K,V > 检查 K 是否实现 Comparable 如果没有提供 Comparator 的地方。否则你会得到 ClassCastException

如评论中所述,https://bugs.openjdk.java.net/browse/JDK-5045147 是引入此问题的问题。根据该问题的讨论,原始修复如下:

BT2:SUGGESTED FIX

Doug Lea writes:

"Thanks! I have a strong sense of deja vu that I've added this before(!) but Treemap.put should have the following trap added."

public V put(K key, V value) {
     Entry<K,V> t = root;

    if (t == null) {
  + if (key == null) {
  + if (comparator == null)
  + throw new NullPointerException();
  + comparator.compare(key, key);
  + }
         incrementSize();
         root = new Entry<K,V>(key, value, null);
         return null;
     }

意图似乎是在 TreeMap 的比较器为 null 的情况下抛出 NPE,或者比较器不接受空键(符合 API 规范)。似乎修复被缩短为一行:

compare(key, key);

定义为:

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

因此,此测试将进行空检查 和类型检查,即转换为 Comparable.